码迷,mamicode.com
首页 > 编程语言 > 详细

Python 简单的多线程聊天

时间:2018-07-09 23:42:17      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:eve   ase   proc   recv   dal   pre   you   anti   ssi   

# client 端
import socket

ip_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 socketserver

class 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 简单的多线程聊天

标签:eve   ase   proc   recv   dal   pre   you   anti   ssi   

原文地址:https://www.cnblogs.com/klvchen/p/9286625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!