脚本:
模拟服务器和客户端交互:
import argparse, socket
from datetime import datetimeIP = "127.0.0.1"
CODING = "utf8"
MAX_BYTES = 65535 # UDP最大长度def server(port): # port:端口号sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCK_DGRAM表示使用udp,SOCK_STREAM表示TCPsock.bind((IP, port)) # 表示进程启动后监听port端口print("Listing at {}".format(sock.getsockname())) #getsockname返回(ip,port)while True: # 不停的接收客户消息,然后告诉客户消息的长度data, address = sock.recvfrom(MAX_BYTES) # 接受客户端发来的消息,data表示消息数据,address表示客户地址text = data.decode(CODING) # 使用utf8解码二进制流,还原成字符串print('The client at {} says {}'.format(address, text))text = 'Your data was {} bytes long'.format(len(data))sock.sendto(text.encode(CODING), address)def client(port):sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)text = 'The time is {}'.format(datetime.now())sock.sendto(text.encode(CODING), ("127.0.0.1", port))print('The os assigned me the address {}'.format(sock.getsockname())) # 客户程序的端口号是操作系统随机分配的,每次进程启动端口都会变化data, address = sock.recvfrom(MAX_BYTES)print('The server {} replied {}'.format(address, data.decode(CODING)))if __name__ == '__main__':choices = {'client': client, 'server': server}parser = argparse.ArgumentParser(description='Send and receive UDP locally')parser.add_argument('role', choices=choices, help='which orle to play: client or server.')parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='UDP port(defuault 1060)')args = parser.parse_args()function = choices[args.role]function(args.p)
结果:
服务端:
客户端:
每次是随机端口