无连接的套接字主要协议是用户数据报协议缩写UDP。必须用SOCK_DGRAM, 即datagram(数据报)。
udp服务器端:
from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpSerSock = socket(AF_INET, SOCK_DGRAM) udpSerSock.bind(ADDR) while True: print('waittinng for meaasge...') data, addr = udpSerSock.recvfrom(BUFSIZ) udpSerSock.sendto(b'[%s] %s' %(bytes(ctime(),encoding='utf-8'), data), addr) print('...received from and returned to: ', addr) udpSerSock.close()
>>>
waittinng for meaasge... ...received from and returned to: ('127.0.0.1', 60073)
udp客户端
from socket import * from time import ctime HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpCliSock = socket(AF_INET, SOCK_DGRAM) while True: data = input('>') if not data: break udpCliSock.sendto( bytes(data, encoding='utf-8'), ADDR) data, addr = udpCliSock.recvfrom(BUFSIZ) if not data: break print(data.decode('utf-8')) udpCliSock.close()
>>>
>nih [Fri Feb 9 13:58:37 2018] nih >hello world [Fri Feb 9 13:59:00 2018] hello world