Add a multi-process solution to the service side
1. Server-side code is as follows:
#!/usr/bin/python#!coding:utf-8ImportOs,sys,time fromSocketImport*defhandleclient (conn):Print '[INFO] handleclient is: {0}'. Format (Os.getpid ()) whileTrue:data= CONN.RECV (1024) if notData:Print '[INFO] handleclient client is stoped .'; Break Print '[INFO] handleclient recive This----{0}'. Format (Data.encode ()) Reply='[INFO] handleclient the information from server to {0}'. Format (Data.decode ()) Conn.send (Reply.encode ()) Conn.close () os._exit (0)if __name__=="__main__": HostIP='127.0.0.1'Port=2048sock=socket (Af_inet,sock_stream) Sock.bind ((Hostip,port)) Sock.listen (5) Print '[INFO] Parent pid is: {0} start listen {1}'. Format (Os.getpid (), (Hostip,port)) whiletrue:conn,addr=sock.accept ()Print '[INFO] Parent get a client {0}'. Format (addr) Cpid=os.fork ()ifCpid = = 0:handleclient (conn)
2, the client terminal code is as follows:
#!/usr/bin/python#!coding:utf-8 fromSocketImport*ImportOs,sysif __name__=="__main__": #Defining Socketshostip='127.0.0.1'Port=2048sock=socket (af_inet,sock_stream) messages=['Hello I am a client'] Messages=messages+sys.argv[1:] Sock.connect ((hostip,port))Print '[INFO] already connected to server' forMessageinchMessages:sock.send (Message.encode ())PrintSOCK.RECV (1024). Decode () Sock.close ()
Python Network Programming second edition