socketserver实现并发操作

时间:2022-05-04 23:59:04

服务端:当无端端口有问题时,改个端口

#Socketserver 实现并发
import socketserver
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):#内置handle方法
        print('conn is',self.request)#conn
        print('addr is',self.client_address)
        while True:
            try:
                #收消息
                data=self.request.recv(1024)
                if not data:break
                print('收到客户端消息是',data)

                #发消息
                self.request.sendall(data.upper())
            except Exception as e:
                print(e)
                break

if __name__ == '__main__':#多线程实现并发,单线程就相当于一个服务员,多线程相当于好几个服务员
    s=socketserver.ThreadingTCPServer(('127.0.0.1',8000),MyServer)#myserver相当于通信循环,
    # threadtcpserver相当于链接循环
    s.serve_forever()

客户端:

from socket import *
ip_port=('127.0.0.1',8000)
back_log=5
buffer_size=1024

tcp_client=socket(AF_INET,SOCK_STREAM)#数据报
tcp_client.connect(ip_port)
while True:
   msg=input('>>').strip()
   if not msg:continue
   if msg== 'quit':break
   tcp_client.send(msg.encode('utf-8'))

   data=tcp_client.recv(buffer_size)
   print('收到服务端发来消息是',data.decode('utf-8'))

tcp_client.close()
#缓冲区为空,输入就会卡住,不往下执行如》》hello,在服务端加上try except 进行异常处理

客户端1与客户端代码相同,