day27_SocketServer模块

目录

    # 服务端.py
    import socketserver
    
    
    class Myserver(socketserver.BaseRequestHandler):
        def handler(self):
            self.data = self.request.recv(1024).strip()
            print(f"{self.client_address[0]} wrote:")
            print(self.data)
            self.request.sendlall(self.data.upper())
    
    
    if __name__ == "__main__":
        HOST, PORT = ('127.0.0.1', 10086)
    
        # 设置allow_reuse_address 允许服务器重用地址
        socketserver.TCPServer.allow_reuse_address = True
        # 创建一个server,将服务器绑定到127.0.0.1:10086
        server = socketserver.TCPServer((HOST, PORT), Myserver)
        # 让server永远执行下去,除非强制执行停止程序
        server.serve_forever()
    
    # 客户端.py
    import socket
    
    HOST, PORT = ('127.0.0.1', 10086)
    data = 'hello'
    
    # 创建一个socket链接,SOCK_STREAM代表使用TCP协议
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n", "utf-8"))
        received = str(sock.recv(1024), "utf-8")
    
    print(f"Sent:	   {data}")
    print(f"Received:  {received}")
    
    
    posted @ 2019-10-20 23:00  W文敏W  阅读(65)  评论(0编辑  收藏  举报