035server端并发聊天

 1 import socketserver
 2 
 3 class MyServer(socketserver.BaseRequestHandler):
 4     def handle(self):    #  里面是每个客户端连接执行的过程
 5         print('服务器启动')
 6         while True:
 7             conn = self.request
 8             print(self.client_address)
 9             while True:
10                 client_data = conn.recv(1024)
11                 print(str(client_data,'utf8'))
12                 print('waiting...')
13                 conn.sendall(client_data)
14             conn.close()
15 
16 if __name__ == '__main__':
17     server = socketserver.ThreadingTCPServer(('127.0.0.1',8888),MyServer)
18     server.serve_forever()       # 激活这个服务器对象
server.py
 1 import  socket
 2 
 3 def connect_server():
 4     sk = socket.socket()
 5     server_address = ('127.0.0.1',8888)
 6     sk.connect(server_address)
 7     return sk
 8 
 9 if __name__ == '__main__':
10     sk = connect_server()
11     while True:
12         inp = input('>>>')
13         if inp == 'exit':
14             break
15         sk.send(bytes(inp,'utf8'))
16         print('waiting...')
17         data = sk.recv(1024)
18         print(str(data,'utf8'))
19     sk.close()
client.py

实现并发聊天:
1、继承socketserver.BaseRequestHandler
2、使用socketserver.ThreadingTCPServer(('127.0.0.1',8888),MyServer)拿到一个服务器对象

要相互发送信息,可以在handle方法里面改成这个,这里的聊天还是有很多缺憾

 

自己调式一下这个执行过程,看python的实现源码

posted @ 2018-03-05 10:47  Alos403  阅读(104)  评论(0编辑  收藏