可以对比下tcp
服务端:
#udp测试 import socket sk = socket.socket(type = socket.SOCK_DGRAM) sk.bind(("127.0.0.1",10050)) # 收发 while 1: msg_str,addr = sk.recvfrom(1024) print("客户端:",msg_str.decode("utf-8"),addr) msg_s = input(">>>") sk.sendto(msg_s.encode("utf-8"),addr) if msg_s=='q': break sk.close()
客户端:
import socket sk = socket.socket(type=socket.SOCK_DGRAM) #sk.connect(("127.0.0.1",10050)) while 1: msg_send = input("我:") sk.sendto(msg_send.encode('utf-8'),("127.0.0.1",10050)) msg_r,addr = sk.recvfrom(1024) print("服务器:",msg_r.decode("utf-8")) if msg_r.decode("utf-8")=='q': break sk.close()
0则评论给“python-UDP聊天室测试”