Advertisement
rfmonk

echo_client.py

May 27th, 2014
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import socket
  5. import sys
  6.  
  7. import argparse
  8.  
  9. host = 'localhost'
  10.  
  11. def echo_client(port):
  12.     """ A simple echo client """
  13.     # Create a TCP/IP socket
  14.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  15.     # Connect the socket to the server
  16.     server_address = (host, port)
  17.     print "Connecting to %s port %s" % server_address
  18.     sock.connect(server_address)
  19.  
  20.     # Send data
  21.     try:
  22.         # Send data
  23.         message = "Test message. This will be echoed"
  24.         print "Sending %s" % message
  25.         sock.sendall(message)
  26.         # Look for the response
  27.         amount_received = 0
  28.         amount_expected = len(message)
  29.         while amount_received < amount_expected:
  30.             data = sock.recv(16)
  31.             amount_received += len(data)
  32.             print "Received: %s" % data
  33.     except socket.errno, e:
  34.         print "Socket error: %s" %str(e)
  35.     except Exception, e:
  36.         print "Other exception: %s" %str(e)
  37.     finally:
  38.         print "Closing connection to the server"
  39.         sock.close()
  40.  
  41. if __name__ == '__main__':
  42.     parser = argparse.ArgumentParser(description='Socket Server Example')
  43.     parser.add_argument('--port', action="store", dest="port", type=int, required=True)
  44.     given_args = parser.parse_args()
  45.     port = given_args.port
  46.     echo_client(port)
  47.  
  48. """ usage, in one terminal fire off echo_server.py --port=xxxx, and in another
  49. terminal fire off the client on the same port"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement