--version 1 Only completes communication between the server/client.
1. Server-side code:
#!/usr/bin/python#!coding:utf-8 fromSocketImport*ImportOs,sysif __name__=="__main__": #Defining Socketshostip='127.0.0.1'Port=2048sock=socket (Af_inet,sock_stream) Sock.bind ((Hostip,port)) Sock.listen (5) Print '[INFO] start listening {0}:{1}'. Format (hostip,port) whileTrue:#accept a connection from a clientCONN,ADDR =sock.accept ()Print '[INFO] have recived a client from {0}'. Format (addr)#interacts with the client until the client exits whileTrue:#receive information from clients, up to 1024 bytes at a timeRECIVEDDATA=CONN.RECV (1024) #because the client sends an empty string when it disconnects, we use this to test that the connection is disconnected if notReciveddata:Print '[WAN] client has been disconnected ...'; Break; Print '[INFO] This is a infomation from client-to {0}'. Format (Reciveddata.decode ())#Send message to clientConn.send ('This inforamtion from server to {0}'. Format (Reciveddata.decode ()). Encode ()) Conn.close ()
2, the client side of the code:
#!/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 first edition