1 import argparse,socket 2 from datetime import datetime 3 4 MAX_BYTES = 65535 5 6 def server(port): 7 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #协议族AF_INET以及数据报类型SOCK_DGRAM.SOCK_DGRAM表示在IP网络上使用UDP协议 8 #要注意的是数据报datagram而不是数据包packet,用了表示应用层数据块传输的官方术语 9 sock.bind(('127.0.0.1',port)) #绑定一个UDP网络地址:一个二元组,包含一个IP地址和一个整形的UDP端口号 10 #端口号要大于1023,否则要管理员权限 11 print('Listening at {}'.format(sock.getsockname())) #查询套接字当前绑定的IP地址和端口号 12 while True: #会进入一个循环不断运行recvfromO 13 data,adress = sock.recvfrom(MAX_BYTES) #最长可接收65535字节的信息,也是UDP数据报可包含的最大长度,没有接收到永远等待 14 #一旦接收到数据报,返回两个值。1 发送该数据报的客户端地址 2 以字节表示数据报的内容 15 text = data.decode('ascii') 16 print('The client at {} says {!r}'.format(adress,text)) 17 text = 'Your data was {} bytes long'.format(len(data)) 18 data = text.encode('ascii') 19 sock.sendto(data,adress) 20 21 def client(port): 22 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 23 text = 'The time is {}'.format(datetime.now()) 24 data = text.encode('ascii') 25 sock.sendto(data,('127.0.0.1',port)) #两个信息:要发送的信息和目标地址。这是向服务器发送数据报的唯一调用 26 print('The OS assigned me the adress {}'.format(sock.getsockname())) 27 data,adress = sock.recvfrom(MAX_BYTES) 28 text = data.decode('asicc') 29 print('The serve {} replied {!r}'.format(adress,text)) 30 if __name__ == '__main__': 31 choices = {'client':client,'server':server} 32 parser = argparse.ArgmentParser(description='Send and receive UDP locally') 33 parser.add_argument('role',choices = choices ,help = 'which role to play') 34 parser.add_argument('-p',metavar = 'PORT',type = int ,default = 1060, 35 help = 'UDP port (default 1060)') 36 args = parser.parse_args() 37 function = choices[args.role] 38 function(args.p)