#!/usr/bin/python ############################################################################# # The chat client ############################################################################# """ Simple chat client for the chat server. Defines a simple protocol to be used with chatserver. """ import socket import sys import select import readline import threading import time from communication import send, receive BUFSIZ = 1024 class MyUserInput(threading.Thread): UserInput='' ReceivedData='' def run(self): while (self.UserInput!="exit" and self.UserInput!="EXIT" and self.ReceivedData!="exit" and self.ReceivedData!="EXIT"): dummy=raw_input("CLIENT >>>") if(self.UserInput!="exit" and self.UserInput!="EXIT" and self.ReceivedData!="exit" and self.ReceivedData!="EXIT"): self.UserInput=dummy else: break time.sleep(0.5) class ChatClient(object): """ A simple command line chat client using select """ def __init__(self, name, host='127.0.0.1', port=3490): self.myUserInput=MyUserInput() self.myUserInput.daemon=True self.myUserInput.start() self.name = name # Quit flag self.flag = False self.port = int(port) self.host = host # Initial prompt self.prompt='[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' # Connect to server at port try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, self.port)) print 'Connected to chat server@%d' % self.port # Send my name... send(self.sock,'NAME: ' + self.name) data = receive(self.sock) # Contains client address, set it addr = data.split('CLIENT: ')[1] self.prompt = '[' + '@'.join((self.name, addr)) + ']> ' except socket.error, e: print 'Could not connect to chat server @%d' % self.port sys.exit(1) def cmdloop(self): oldUserInput='' while not self.flag: try: #sys.stdout.write(self.prompt) #sys.stdout.flush() # Wait for input from stdin & socket inputready, outputready,exceptrdy = select.select([self.sock], [],[]) for i in inputready: #if i == 0: # data = sys.stdin.readline().strip() # if data: send(self.sock, data) if i == self.sock: data = receive(self.sock) if not data: print 'Shutting down.' self.flag = True break else: sys.stdout.write(data + '\n') sys.stdout.flush() if(oldUserInput!=self.myUserInput.UserInput): oldUserInput=self.myUserInput.UserInput send(self.sock,self.myUserInput.UserInput) except KeyboardInterrupt: print 'Interrupted.' self.sock.close() break if __name__ == "__main__": import sys if len(sys.argv)<3: sys.exit('Usage: %s chatid host portno' % sys.argv[0]) client = ChatClient(sys.argv[1],sys.argv[2], int(sys.argv[3])) client.cmdloop()