二、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]  
相關文章
相關標籤/搜索