#!/usr/bin/env python # Basic Chat Client- socketclient.py import socket, sys # host = sys.argv[1] # Uses first command line argument as hostname # textport = sys.argv[2] # Uses second argument as port number if sys.argv: host = sys.argv[1] textport = sys.argv[2] else: print "What computer would you like to connect to?: ", host = sys.stdin.readline() print "Using what port?: ", textport = sys.stdin.readline() name = raw_input('What is your name, friend?: ') # Establish Connection try: # UDP Declaration(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create socket s( Uses IPv4 , Uses TCP ) except socket.error, e: # Finds port for ( Port name, Protocol name ) print "Strange error creating socket: %s" % e sys.exit(1) try: port = int(textport) except ValueError: # Didn't work, try protocol name search try: # If we were to use UDP: , 'udp') port = socket.getservbyname(textport, 'tcp') # Finds port for ( Port name, Protocol name ) # print "Oh, port %(string)s is actually port %(int)d. "\ # % {'string' : textport, 'int': port}, # print "Ok, I got that!" except socket.error, e: # General I/O communication problem print "Couldn't find your port: %s" % e sys.exit(1) # print "Connecting socket to %(host)s on port %(port)d... " \ # % {'host':host, 'port':port}, try: s.connect((host, port)) # print "completed!\n" except socket.gaierror, e: # Error looking up address information print "Address-related error connecting to server: %s" % e sys.exit(1) except socket.error, e: # General I/O communication problem print "Connection error: %s" % e sys.exit(1) print "\nConnected to", s.getpeername() # Send Name To Server s.sendall(name) # Chat Function while 1: data = raw_input(name + ' says?: ') s.sendall(data) print " Awaiting Response.... " data = s.recv(2048) if not len(data): break print "Server says: %s" % data #except (KeyboardInterrupt, SystemExit): # raise