Create a process for each TCP connection you create.
The code is as follows:
#Coding:utf-8ImportSocketImportOSImportSYSImportSignalImporterrno fromTimeImportCTimedefHANLDE_SIGCHLD (A, B): (PID, status)=os.wait ()Print 'Child %d Finish, status =%d'%(PID, status)defhandle_connection (Client_socket, client_address): whileTrue:data= CLIENT_SOCKET.RECV (1024) if notData:Print 'Disconnect', Client_address client_socket.close () Break; Else: Client_socket.send ('[%s]%s'% (CTime (), data))#echo Messageif __name__=='__main__': signal.signal (signal. SIGCHLD, HANLDE_SIGCHLD)#handling functions for installing SIGCHLDServer_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 pid=os.fork ()ifPID = =0:server_socket.close () handle_connection (Client_socket, client_address) sys.exit (0 ) #prevent the child process from forgetting exit elifPID >0:client_socket.close ()#must be closed
Here are a few things to note:
1. The server socket needs to be closed in the child process because the child process requires only the client socket.
2. The parent process must close the client socket because the socket is based on a reference count and the parent process does not close, causing the socket to never actually close.
3. Pay attention to the demise of the processing sub-process and avoid the zombie process. You cannot use the wait or Waitpid function directly, because the function will block the process so that it does not have concurrency capability.
Python Learning Notes (v) multi-process implementation of concurrent servers