#!/usr/bin/python # asteroid_client.py # A model client for the asteroid_server # Jure Skvarc, March 1999 # import socket import select from sys import * from string import * import getopt import os import errno class Asteroid_client: # Create a socket def __init__(self, host, port): self.port = port self.host = host self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self): err = self.sock.connect_ex(self.host, self.port) # If connection did not succeed, exit if err != 0: print 'Can not connect to server', host, 'at port', port print 'Reason:', os.strerror(err) exit() def get(self): return self.sock.recv(1024) def send(self, request): self.sock.send(request) def close(self): self.sock.close() def get_answer(self, timeout): ins = 1 ans = '' # The answer may be pretty long, so be ready to receive in parts while ins: # Wait for the information a, b, c = select.select([self.sock], [], [], 10) if len(a) > 0: ans1 = self.get() if len(ans1) == 0: ins = 0 ans = ans + ans1 if ans[-1] == '\0': ins = 0 ans = ans[0:-1] else: # Timeout, end the loop ins = 0 return ans # Default host address host = '127.0.0.1' # Port number for the astreoid server port = 58972 # User id id = 'Jure' if len(argv) < 2: print "Usage:: asteroid_client.py server_address id" exit(1) # Default host address host = argv[1] # User id id = argv[2] clnt = Asteroid_client(host, port) # try to connect to the server clnt.connect() # send id clnt.send(id + '\0') # Get an intro message hello = clnt.get() # Display the intro message print hello[:-2] # Close the connection clnt.close() del clnt # Repeat indefinetely while 1: try: request = raw_input('Asteroid>') except: print "Exit" exit() # Server wants that requests end with a \0 request = request + "\0" # create a socket clnt = Asteroid_client(host, port) # connect to the server clnt.connect() # send id clnt.send(id + '\0') # Receive the intro string but do not display it hello = clnt.get() # Send the request clnt.send(request) # get the answer ans = clnt.get_answer(10) # Close the connection clnt.close() # Split the answer into lines lines = split(ans, "\n") # Display the result for a in lines: if len(a) > 0 and a[-1] == '\0': a = a[0:-1] print a if a == 'Exit': exit()