Add multi-threaded solutions to the server
1. The service-side code is as follows:
This version does not really play the role of multithreading, the main reason is T.join (), the future version will improve the problem * * *
#!/usr/bin/python#!coding:utf-8ImportOs,sys,time fromSocketImport*ImportThreadingdefhandleclient (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 () sys.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) T=threading. Thread (target=handleclient,args=(conn,)) T.start () T.join ( )
2, the client 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 Third edition