The previous article wrote a simple single-threaded simple chat room with a question and answer. This time we use the Socketserver module to build a multi-threaded asynchronous chat room.
| 12345678910111213141516171819 |
# -*- coding:utf-8 -*-importSocketServerclassmysocketclass(SocketServer.BaseRequestHandler): defhandle(self): client_information=self.request; #获取客户端的信息,相当于accept client_information.send(‘Welcome!‘); whileTrue: data =client_information.recv(1024) ifdata ==‘exit‘: client_information.close(); else: print‘**Client**:‘,(data); client_information.send("ok");if__name__==‘__main__‘: ip_add=(‘127.0.0.1‘,9998); server=SocketServer.ThreadingTCPServer(ip_add,mysocketclass); server.serve_forever(); |
Client
| 12345678910111213 |
#-*-coding:utf-8-*-importsocketsocket_object=socket.socket();ip_add=(‘127.0.0.1‘,9998);socket_object.connect(ip_add);whileTrue: print‘**Server**:‘,(socket_object.recv(1024)) seend_content=raw_input(‘Client:‘); socket_object.send(seend_content) ifseend_content==‘exit‘: socket_object.connect.close(); |
As you can see from the code, the content of the client is unchanged. The change is that the service side uses the module socketserver
Run:
Next time we add database, implement login, register chat room
Original address: HTTP://REXYAN.CN/ARTICLE/25
Rex Blog All rights reserved
Python Socket Simple Chat Room 2