2、socket+threading编程之UDP

 

 1 Server-UDP
 2 
 3 #coding:utf8
 4 
 5 from socket import socket
 6 
 7 import threading
 8 
 9 def response(sock,data,addr):
10 
11   node = {'1':1,'2':2,'3':3}
12 
13   if node.has_key(data):
14 
15     sock.sendto(node[data],addr)
16 
17     print 'Sent server to:',addr
18 
19   else:
20 
21     sock.sendto('Error')
22 
23     print 'error code'
24 
25 def server():
26 
27   server = socket(AF_INET,SOCK_DGRAM)
28 
29   address = ('127.0.0.1',8888)  #如果挂在服务器上的话,用0.0.0.0
30 
31   server.bind(address)
32 
33   while 1:      #while 1比while True性能好一点
34 
35     data,addr = server.recvfrom(4096)
36 
37     response = threading.Thread(target=response,args=(server,data,addr))
38 
39     response.start()
40 
41 if __name__ == '__main__':
42 
43   server()
44 
45 '''
46 
47 这个就不写注释了,UDP不需要建立连接,所以监听什么的都免了,注意与TCP的区别
48 
49 '''
50 
51 Client-UDP
52 
53 #coding:utf8
54 
55 from socket import socket
56 
57 def client(data):
58 
59   addr = ('127.0.0.1',8888)
60 
61   client = socket(AF_INET,SOCK_DGRAM)
62 
63   try:
64 
65     client.connect())
66 
67   except Exception as e:
68 
69     print 'Connect Error :%s'%e
70 
71   client.sendall(data)
72 
73   server_response = client.recv(4096)
74 
75   return server_response
76 
77 if __name__ == '__main__':
78 
79   data = raw_input('input data')
80 
81   node = {data:client(data)}
82 
83   if node [data] == 'Error':
84 
85     print 'Error data'
86 
87   else:
88 
89     print node[data]  

 

posted @ 2017-11-19 10:35  MrHacks  阅读(179)  评论(0编辑  收藏  举报