Python Socket 簡單聊天室2

來源:互聯網
上載者:User

標籤:部落格   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.