基于socketserver实现并发tcp、udp

时间:2021-03-24 23:57:11

1.基于socketserver实现并发-tcp

#服务端
import socketserver


class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):

        #print(self.client_address) #客户端地址
        #print(self.request)        ##self.request=conn 套接字对象
        while True:
            try:
                data = self.request.recv(1024)
                if len(data) == 0: break
                print()
                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() #代表连接循环  #循环建立连接,每建立一个连接就会启动一个线程+调用MyHandler类产生一个对象, #该对象下面的handle方法,专门与刚刚建立好的连接做通信循环 #客户端地址
        #print(self.request)        ##self.request=conn 套接字对象
        while True:
            try:
                data = self.request.recv(1024)
                if len(data) == 0: break
                print()
                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() #代表连接循环
    #循环建立连接,每建立一个连接就会启动一个线程+调用MyHandler类产生一个对象, #该对象下面的handle方法,专门与刚刚建立好的连接做通信循环

 

#客户端
import socket

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

phone.connect(('127.0.0.1',8080))

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

 

1.基于socketserver实现并发-ucp

 

 

#服务端
import socketserver


class MyHandeler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0]   #request是个元组,元组的第一个是数据,第二个是一个套接字对象
        print('消息', data)
        self.request[1].sendto(data.upper(), self.client_address)  #self.request[1] 是套接字对象


if __name__ == '__main__':
    s = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyHandeler)
    s.serve_forever()
#request是个元组,元组的第一个是数据,第二个是一个套接字对象
        print('消息', data)
        self.request[1].sendto(data.upper(), self.client_address)  #self.request[1] 是套接字对象


if __name__ == '__main__':
    s = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyHandeler)
    s.serve_forever()
#客户端

import socket
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
    msg=input('>>>>>>>').strip()
    #msg='111111111111'
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    data,server_addr=client.recvfrom(1024)
    print(data)

client.close()