Using the socket module in Python to implement the UDP protocol, here to write a simple server and client. In order to illustrate the application of UDP in network programming, we do not write the graphic, and open the UDP client and the server on the two computers separately.
UDP: User Datagram Protocol, which is a non-connection oriented protocol. Using this protocol does not require two applications to establish a connection first. The UDP protocol does not provide error recovery and cannot provide data retransmission, so the protocol transmits data with poor security.
Client
Python3 can only send and receive binary data, requires explicit transcoding
from socket import *host = ‘192.168.48.128‘ # 这是客户端的电脑的ipport = 13141 #接口选择大于10000的,避免冲突bufsize = 1024 #定义缓冲大小addr = (host,port) # 元祖形式udpClient = socket(AF_INET,SOCK_DGRAM) #创建客户端while True: data = input(‘>>> ‘) if not data: break data = data.encode(encoding="utf-8") udpClient.sendto(data,addr) # 发送数据 data,addr = udpClient.recvfrom(bufsize) #接收数据和返回地址 print(data.decode(encoding="utf-8"),‘from‘,addr)udpClient.close()
Server
also requires explicit transcoding
from socket import *from time import ctimehost = ‘‘ #监听所有的ipport = 13141 #接口必须一致bufsize = 1024addr = (host,port) udpServer = socket(AF_INET,SOCK_DGRAM)udpServer.bind(addr) #开始监听while True: print(‘Waiting for connection...‘) data,addr = udpServer.recvfrom(bufsize) #接收数据和返回地址 #处理数据 data = data.decode(encoding=‘utf-8‘).upper() data = "at %s :%s"%(ctime(),data) udpServer.sendto(data.encode(encoding=‘utf-8‘),addr) #发送数据 print(‘...recevied from and return to :‘,addr)udpServer.close()
Welcome to further Exchange this blog post related content:
Blog Park Address: http://www.cnblogs.com/AsuraDong/
CSDN Address: Http://blog.csdn.net/asuradong
You can also write to communicate: [email protected]
Welcome reprint , but please specify the source:)
Python3 simple servers and clients that implement the UDP protocol