1. 程式人生 > >基於socketserver模組實現併發的套接字(tcp、udp)

基於socketserver模組實現併發的套接字(tcp、udp)

tcp
服務端:

import socketserver


class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
#通訊迴圈
while True:
# print(self.client_address)
# print(self.request) #self.request = conn

try:
data=self.request.recv(1024)
if len(data) == 0:break

self.request.send(data.upper())
except ConnectionResetError:
break


if __name__ == '__main__':
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)

s.serve_forever() # 代表連線迴圈
# 迴圈建立連線,每建立一個連線就會啟動一個執行緒(服務員)+呼叫Myhanlder類產生一個物件,呼叫該物件下的handle方法,專門與剛剛建立好的連線做通訊迴圈


客戶端1:
import socket

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080)) # 指定服務端ip和埠

while True:
# msg=input('>>: ').strip() #msg=''
msg = 'client33333' # msg=''
if len(msg) == 0:continue
phone.send(msg.encode('utf-8'))
data=phone.recv(1024)
print(data)



phone.close()


客戶端2:同客戶端1
...
udp
服務端:
import socketserver

class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
#通訊迴圈
# print(self.client_address)
# print(self.request)

data=self.request[0]
print('客戶訊息',data)
self.request[1].sendto(data.upper(),self.client_address)


if __name__ == '__main__':
s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
s.serve_forever()

客戶端:
import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #資料報協議-》udp

while True:
# msg=input('>>: ').strip() #msg=''
msg='client444444'

client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,server_addr=client.recvfrom(1024)
print(data)

client.close()