Python Learning Notes (vi) multi-process implementation Concurrent Server

Source: Internet
Author: User

This is more straightforward than a multi-process, creating a new thread per accept a new connection. The code is as follows:

#Coding:utf-8ImportSocketImportSYSImporterrnoImportThreading fromTimeImportCTimeclassClientthread (Threading. Thread):def __init__(self, Client_socket, client_address): Threading. Thread.__init__(self) self.client_socket=Client_socket self.client_address=client_addressdefRun (self): self.handle_connection ()defhandle_connection (self): whileTrue:data= SELF.CLIENT_SOCKET.RECV (1024)            if  notData:Print 'Disconnect', Self.client_address self.client_socket.close () Break; Else: Self.client_socket.send ('[%s]%s'% (CTime (), data))#echo Messageif __name__=='__main__': Server_socket=Socket.socket (socket.af_inet, socket. SOCK_STREAM) listen_address= ('localhost', 9981) server_socket.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR,1) Server_socket.bind (listen_address) Server_socket.listen (10)     whileTrue:Try: (Client_socket, client_address)=server_socket.accept ()exceptIOError, E:ifE.errno = =errno. EINTR:Continue #Keep waiting .            Else:                Raise #throw an exception outward        Print 'Got Connection from', client_address t=Clientthread (Client_socket, client_address) T.start ()

Note that the thread here cannot join, otherwise it will block the main thread and lose the concurrency capability.

In addition, threads in Python do not need to be detach.

Python Learning Notes (vi) multi-process implementation Concurrent Server

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.