基于python中的TCP及UDP(详解)
python中是通过套接字即socket来实现UDP及TCP通信的。有两种套接字面向连接的及无连接的,也就是TCP套接字及UDP套接字。
TCP通信模型
创建TCP服务器
伪代码:
ss = socket() # 创建服务器套接字 ss.bind() # 套接字与地址绑定 ss.listen() # 监听连接 inf_loop: # 服务器无限循环 cs = ss.accept() # 接受客户端连接 comm_loop: # 通信循环 cs.recv()/cs.send() # 对话(接收/发送) cs.close() # 关闭客户端套接字 ss.close() # 关闭服务器套接字#(可选)
TCP时间戳服务器:
import socket from time import ctime HOST = '' PORT = 8099 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print("等待连接......") tcpCliSock, addr = tcpSerSock.accept() print("...接收到连接:", addr) while True: data = tcpSerSock.recv(BUFSIZE) if not data: break tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data)) tcpCliSock.close() tcpSerSock.close()
创建TCP客户端:
伪代码:
cs = socket() # 创建客户端套接字 cs.connect() # 尝试连接服务器 comm_loop: # 通信循环 cs.send() / cs.recv() # 对话(发送/接收) cs.close() # 关闭客户端套接字
TCP时间戳客户端:
import socket HOST = 'localhost' PORT = 8099 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = input("> ") if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZE) if not data: break print(data) tcpCliSock.close()
UDP通信模型
创建UDP服务器
伪代码:
ss = socket() # 创建服务器套接字 ss.bind() # 绑定服务器套接字 inf_loop: # 服务器无限循环 cs = ss.recvfrom()/ss.sendto() # 关闭(接收/发送) ss.close() # 关闭服务器套接字
UDP时间戳服务器:
import socket from time import ctime HOST = '' PORT = 8099 BUFSIZE = 1024 ADDR = (HOST, PORT) udpSerSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udpSerSock.bind(ADDR) while True: print("等待连接......") data, addr = udpSerSock.recvfrom(BUFSIZE) udpSerSock.sendto('[%s] %s' % (ctime(), data), addr) print("...接收到连接:", addr) udpSerSock.close()
创建UDP客户端
伪代码:
cs = socket() # 创建客户端套接字 comm_loop: # 通信循环 cs.sendto() / cs.recvfrom() # 对话(发送/接收) cs.close() # 关闭客户端套接字
UDP时间戳客户端:
import socket HOST = 'localhost' PORT = 8099 BUFSIZE = 1024 ADDR = (HOST, PORT) udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udpCliSock.connect(ADDR) while True: data = input("> ") if not data: break udpCliSock.sendto(data, ADDR) data, ADDR = udpCliSock.recvfrom(BUFSIZE) if not data: break print(data) udpCliSock.close()
相关推荐
CloudXli 2020-04-20
lenchio 2020-03-27
OwenJi 2020-01-17
batoom 2011-09-23
书虫媛 2020-05-03
阿艾辣悟叩德 2020-04-20
架构技术交流 2020-04-14
fsl 2020-07-04
fibbery学习笔记 2020-06-27
MAC2007 2020-06-06
SoarFly00 2020-02-11
Ongoingcre 2013-04-01
bapinggaitianli 2019-12-19
qscool 2019-12-23
furongwei 2019-12-17
typhoonpython 2019-12-11
sapliang 2019-12-10
huangzonggui 2019-12-09
kevinli 2019-12-09