Python中基於socketserver實現併發的socket

一、基於TCP協議:

服務端:socket

 1 import socketserver
 2 
 3 class MyHandler(socketserver.BaseRequestHandler):
 4     def handle(self):
 5         #通訊循環
 6         while True:
 7             # print(self.client_address)
 8             # print(self.request) #self.request=conn
 9 
10             try:
11                 data=self.request.recv(1024)
12                 if len(data) == 0:break
13                 self.request.send(data.upper())
14             except ConnectionResetError:
15                 break
16 
17 
18 if __name__ == '__main__':
19     s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)
20 
21     s.serve_forever()  # 表明鏈接循環
22     # 循環創建鏈接,每創建一個鏈接就會啓動一個線程(服務員)+調用Myhanlder類產生一個對象,調用該對象下的handle方法,專門與剛剛創建好的鏈接作通訊循環

客戶端:spa

 1 import socket
 2 
 3 phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 4 phone.connect(('127.0.0.1',8080)) # 指定服務端ip和端口
 5 
 6 while True:
 7     # msg=input('>>: ').strip() #msg=''
 8     msg = 'client33333'  # msg=''
 9     if len(msg) == 0:continue
10     phone.send(msg.encode('utf-8'))
11     data=phone.recv(1024)
12     print(data)
13 
14 
15 phone.close()

 

 

二、基於UDP協議:

服務端:線程

 1 import socketserver
 2 
 3 class MyHandler(socketserver.BaseRequestHandler):
 4     def handle(self):
 5         #通訊循環
 6         # print(self.client_address)
 7         # print(self.request)
 8 
 9         data=self.request[0]
10         print('客戶消息',data)
11         self.request[1].sendto(data.upper(),self.client_address)
12 
13 
14 if __name__ == '__main__':
15     s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
16     s.serve_forever()

客戶端:code

 1 import socket
 2 
 3 client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #數據報協議-》udp
 4 
 5 while True:
 6     # msg=input('>>: ').strip() #msg=''
 7     msg='client444444'
 8 
 9     client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
10     data,server_addr=client.recvfrom(1024)
11     print(data)
12 
13 client.close()
相關文章
相關標籤/搜索