服务器端:
#!/usr/bin/env python 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 'waiting for message...' data, addr = udpSerSock.recvfrom(BUFSIZ)##监听并接受客户端发的消息 udpSerSock.sendto('[%s] %s' % ( ##给消息加上时间戳并返回给客户端 ctime(), data), addr) print '...received from and returned to:', addr udpSerSock.close()
客户端:
#!/usr/bin/env python from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpCliSock = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input('> ') if not data: break udpCliSock.sendto(data, ADDR) ##给服务器发送数据 data, ADDR = udpCliSock.recvfrom(BUFSIZ) ##客户端接受带时间戳的数据 if not data: break print data udpCliSock.close()