Server:
Import socketimport sysimport argparsehost = ' localhost ' data_payload = 2048backlog = 5def echo_server (port): ' A simple EC Ho server ' #Create a TCP socketsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #Enable Reuse address/portsock.setsockopt (socket). Sol_socket, SOCKET. SO_REUSEADDR, 1) #Bind the socket to the portserver_address = (host, port) print "Starting up Echo server on%s port%s"%s Erver_addresssock.bind (server_address) #Listen to clients, backlog argument specifies the max number of queued connections Sock.listen (5) while True:print "waiting-to-receive message from client" client, address = sock.accept () data = Client.recv (d ata_payload) If Data:print "data:%s"%dataclient.send (data) print "Send%s bytes back to%s"% (len (data), address) #End Conn Ectionclient.close () If __name__== "__main__":p arser = Argparse. Argumentparser (description= ' Socket Server Example ') parser.add_argument ('--port ', action= ' store ', dest= ' Port ', type= int, required=true) Given_args = Parser.parse_args () port = Given_args.portecho_server (Port)
Client:
Import socketimport sysimport argparsehost = ' localhost ' def echo_client (port): ' A simple echo client ' #Create a TCP/IP s Ocketsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #Connect the socket to the serverserver_address = (host, port) print "Connecting to%s port%s"%server_addres Ssock.connect (server_address) #Send datatry: #Send datamessage = "Test message. This would be echoed. " Print "Sending%s"%messagesock.sendall (message) #Look for the responseamount_received = 0amount_expected = Len (message) While amount_received < Amount_expected:data = Sock.recv (+) amount_received +=len (data) print "receviced:%s"% Dataexcept socket.error, E:print "Socket error:%s"%STR (e) except Exception, E:print "other Exception:%s"%str (e) finall Y:print "Closing connection to the server" Sock.close () if __name__== "__main__":p arser = Argparse. Argumentparser (description= ' Socket Client Example ') parser.add_argument ('--port ', action= ' store ', dest= ' Port ', type= int, required=true) Given_args = Parser.parSe_args () port = given_args.portecho_client (port)
Python Simple client/server application