UDP服务器
由于UDP服务器不是面向连接的,所以不用像TCP服务器那样那么多设置,直接等待进来的连接就好了
伪代码:
ss = socket() #创建一个服务器套接字 ss.bind() #绑定服务器套接字 inf_loop: cs = ss.recvfrom()/ss.sendti() ss.close()
UDP server
#!/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()
udp client:
#!/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()
server运行:
[nanjing3@master python]$ ./tsUserv.py waiting for message... ...received from and returned to: ('127.0.0.1', 36960) waiting for message... ...received from and returned to: ('127.0.0.1', 41671) waiting for message... ...received from and returned to: ('127.0.0.1', 41671) waiting for message... ...received from and returned to: ('127.0.0.1', 41671) waiting for message...
client 运行:
[nanjing3@master python]$ ./tsUcli.py >1 [Wed Nov 7 03:39:06 2012] 1 >2 [Wed Nov 7 03:39:10 2012] 2 >hi, [Wed Nov 7 18:32:33 2012] hi,