Python写的简陋版一对一聊天工具,全双工
好该睡觉了,明天还要上班~~~直接上代码,后面再总结
1 import threading 2 import os 3 import socket 4 5 6 def RecvProcess ( UDP_Socket, LocalAddrInfo ): 7 print 'UDP Recver is UP' 8 while 1: 9 data, PeerAddr = UDP_Socket.recvfrom ( 1024 ) 10 if data == 'local exit' and LocalAddrInfo == PeerAddr: 11 print 'RecvProcess was terminated!' 12 break 13 #data = raw_input () 14 print '%s(MessageFrom %s:%d)' % ( data, PeerAddr[0], PeerAddr[1] ) 15 16 if __name__ == '__main__': 17 #Create UDP socekt 18 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 19 #Get local machine name 20 myname = socket.getfqdn(socket.gethostname()) 21 myaddr = socket.gethostbyname(myname) 22 addrinfo = ( myaddr, 5060 ) 23 print myaddr 24 s.bind( addrinfo ) 25 #Start the Recv process 26 threadrecv = threading.Thread ( target = RecvProcess, args = (s, addrinfo) ) 27 threadrecv.start () 28 while 1: 29 val = raw_input() 30 if val == 'exit': 31 s.sendto ( 'local exit', addrinfo ) 32 break 33 s.sendto ( val, ( '192.168.3.36', 5060) ) 34 print 'quit'