socketserver模块实现并发

服务端

import socketserver


class MyRequestHandle(socketserver.BaseRequestHandler):  #定义一个类,引用sockerserver的基类socketserver.BaseRequestHandler
    def handle(self):
        print(self.request)                       # 此步,相当于tcp套接字下面2步
        # conn, client_addr = phone.accept()
        # print(client_addr)

        while True:
            try:
                cmd = self.request.recv(1024)      # self.request 相当于conn
                if cmd == 0: break
                self.request.send(cmd.upper())
            except Exception:
                break


s = socketserver.ThreadingTCPServer(('127.0.0.1', 8899), MyRequestHandle)
s.serve_forever()

客户端 (开启多个客户端)

from socket import *

client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8899))
while True:
    cmd=input('小写转换大写>>>>'.strip())
    if len(cmd)==0:continue
    client.send(cmd.encode('utf-8'))

    msg=client.recv(1024)
    print(msg.decode('utf-8'))


执行如下

客户端1:
请输入命令>>:ls
LS
请输入命令>>:

客户端2:
请输入命令>>:hello
HELLO

你可能感兴趣的:(socketserver模块实现并发)