基于socketserver模块实现并发的套接字(tcp、udp)

时间:2021-10-13 23:57:26
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()