Python Socket Simple Chat Room 2

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.