socketserver 模块

socketserver 模块 是实现多个客户端与服务端通话的 (tcp协议下的socket)

服务端相对socket模块有固定的格式,客户端无变化

  服务端

import socketserver
class Server(socketserver.BaseRequestHandler):
    def handle(self):
        while 1:
            from_client = self.request.recv(1024).decode("utf-8")
            print("客户端说:",from_client)
            to_client = input("服务端说:")
            self.request.send(to_client.encode("utf-8"))

if __name__ == '__main__':
    server_ip = ("127.0.0.1",8001)
    a = socketserver.ThreadingTCPServer(server_ip,Server)
    a.serve_forever()

  客户端

import socket
client = socket.socket()
server_ip = ("127.0.0.1",8001)
client.connect(server_ip)
while 1 :
    to_server = input("客户端说:")
    client.send(to_server.encode('utf-8'))
    from_server = client.recv(1024).decode('utf-8')
    print("服务端说:",from_server)

  

posted on 2019-01-07 16:45  哎呀!土豆  阅读(103)  评论(0编辑  收藏  举报

导航