socketserver实现并发通讯

socketserver实现并发通讯

#server端
import socketserver

class Myserver(socketserver.BaseRequestHandler):
    def handle(self): #自动的触发了handle方法,并且sele.request=conn,handle不能变,一直是这个
        while True:
            msg = self.request.recv(1024).decode("utf-8")
            self.request.send(msg.upper().encode("utf-8"))
            print(msg)

server = socketserver.ThreadingTCPServer(("127.0.0.1",9000),Myserver)
server.serve_forever()

#client端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
    sk.send(b"hello")
    msg =sk.recv(1024)
    print(msg)


sk.close

#client1端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
    sk.send(b"hello.mo")
    msg =sk.recv(1024)
    print(msg)


sk.close

#client2端
import socket
sk = socket.socket()
sk.connect(("127.0.0.1",9000))
while True:
    sk.send(b"hello.yang")
    msg =sk.recv(1024)
    print(msg)


sk.close
posted @ 2021-06-09 21:45  小杨的冥想课  阅读(41)  评论(0编辑  收藏  举报