这里定义了一个 UDPServer 和 UDPClient。这里创建一个 TCP
服务程序,服务器会把客户发送过来的字符串加上一个时间戳,然后显示,并返回客户端。
UDPServer.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| from socket import * from time import ctime
HOST = '' PORT = 20001 BUFSIZE = 1024 ADDR = (HOST, PORT) udpSerSock = socket(AF_INET, SOCK_DGRAM) udpSerSockbind(ADDR) while True: print 'waiting for message...' data, addr = udpSerSock.recvfrom(BUFSIZE) udpSerSock.sendto('[%s] %s' % (ctime(), data), addr) print'received from %s >> %s' % (addr, data) udpSerSock.close()
|
UDPClient.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from socket import * HOST = 'localhost' PORT = 20001 BUFSIZE = 1024 ADDR = (HOST, PORT) udpClientSock = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input('Enter the message you want to send >') if not data: break udpClientSock.sendto(data, ADDR) data, ADDR = udpClientSock.recvfrom(BUFSIZE) if not data: break print data udpClientSock.close()
|