Python 簡單的多線程聊天

來源:互聯網
上載者:User

標籤:eve   ase   proc   recv   dal   pre   you   anti   ssi   

# client 端import socketip_port = (‘127.0.0.1‘, 8091)sk = socket.socket()sk.connect(ip_port)print("用戶端啟動: ")while True:    inp = input(">>>")    sk.sendall(bytes(inp, "utf8"))    if inp == ‘exit‘:        break    server_response = sk.recv(1024)    print(str(server_response, "utf8"))sk.close()# server 端import socketserverclass MyServer(socketserver.BaseRequestHandler):    def handle(self):        print("伺服器啟動...")        while True:            conn = self.request            print(self.client_address)            while True:                client_data = conn.recv(1024)                print(str(client_data, "utf8"))                print("waiting...")                server_response = input(">>>")                conn.sendall(bytes(server_response, "utf8"))            conn.close()if __name__ == ‘__main__‘:    server = socketserver.ThreadingTCPServer((‘127.0.0.1‘,8091), MyServer)    server.serve_forever()   # 這裡會執行 handle 方法,所以 handle 方法裡是編寫程式邏輯。
建立一個socketserver 至少分以下幾步

First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests.
  
Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.

Then call the handle_request() or serve_forever() method of the server object to process one or many requests.

Finally, call server_close() to close the socket.

Python 簡單的多線程聊天

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.