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