標籤:部落格 pac reading cell imp 內容 簡單 object plain
上篇文章寫了一個簡單的單線程的一問一答的簡單聊天室。這次我們使用SocketServer模組搭建一個多線程非同步聊天室。
| 12345678910111213141516171819 |
# -*- coding:utf-8 -*- import SocketServerclass mysocketclass(SocketServer.BaseRequestHandler): def handle(self): client_information=self.request; #擷取用戶端的資訊,相當於accept client_information.send(‘Welcome!‘); while True: data = client_information.recv(1024) if data == ‘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(); |
用戶端
| 12345678910111213 |
#-*-coding:utf-8-*- import socketsocket_object=socket.socket();ip_add=(‘127.0.0.1‘,9998);socket_object.connect(ip_add); while True: print ‘**Server**:‘,(socket_object.recv(1024)) seend_content=raw_input(‘Client:‘); socket_object.send(seend_content) if seend_content==‘exit‘: socket_object.connect.close(); |
從代碼可以看出,用戶端的內容是沒變的。變動的是服務端採用了模組SocketServer
運行:
下一次我們加上資料庫,實現登入,註冊的聊天室
原文地址:http://rexyan.cn/article/25
Rex部落格保留所有權利
Python Socket 簡單聊天室2