def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.run() receiver = MessageReceiver(self, self.connection) receiver.start() while alive: msg = raw_input() msg = msg.split() request = msg[0] if len(msg)==2: content = msg[1] else: content = None payload = json.dumps({'request':request, 'content':content}) self.send_payload(payload) receiver.join() self.disconnect()
class Client: def __init__(self, host, serverPort): self.host = host self.serverPort = serverPort self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((self.host, self.serverPort)) self.jsonObject = None def disconnect(self): self.connection.close() try: self.messageReceiver.stop() except: pass def rawInput(self): request = raw_input("Request type: ") if (request in ["login", "msg"]): content = raw_input("Content: ") self.jsonObject = json.dumps( { 'request': request, 'content': content }, indent=4) else: self.jsonObject = json.dumps({'request': request}, indent=4) return request def receiveMessage(self): self.messageReceiver = MessageReceiver(self.connection) self.messageReceiver.start() def send(self): self.connection.send(self.jsonObject)
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) while True: userInput = raw_input("") liste = [] if " " in userInput: content = "" liste = userInput.split(" ") request = liste[0] for i in range(1, len(liste)): content += liste[i] if(i != len(liste)-1): content += " " else: request = userInput content = None self.send_payload(request, content) if request == "logout": self.disconnect() reciever = MessageReceiver(self, self.connection) reciever.daemon = True reciever.start()
class Client: def __init__(self, host, serverPort): self.host = host self.serverPort = serverPort self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((self.host,self.serverPort)) self.jsonObject = None def disconnect(self): self.connection.close() try: self.messageReceiver.stop() except: pass def rawInput(self): request = raw_input("Request type: ") if(request in ["login", "msg"]): content = raw_input("Content: ") self.jsonObject = json.dumps({'request': request, 'content': content}, indent=4) else: self.jsonObject = json.dumps({'request': request}, indent=4) return request def receiveMessage(self): self.messageReceiver = MessageReceiver(self.connection) self.messageReceiver.start() def send(self): self.connection.send(self.jsonObject)
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) receiver = MessageReceiver(self, self.connection) receiver.start() while True: command = input("> ") if len(command.split(" ")) > 1: # It's a command with content command = command.split(" ") if command[0] == "login": raw_message = {'request': 'login', 'content': command[1]} elif command[0] == "msg": messageString = "" for i in command[1:]: messageString += i + ' ' messageString = messageString[:-1] raw_message = {'request': 'msg', 'content': messageString} else: print("Unknown command! Please try again.") continue else: # It's a command without content if command == 'logout' or command == 'help' or command == 'history' or command == 'names': raw_message = {'request': command, 'content': None} else: print("Unknown command! Please try again.") continue JSON_message = json.dumps(raw_message) self.send_payload(JSON_message.encode("utf-8"))
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) while True: userInput = raw_input("") liste = [] if " " in userInput: content = "" liste = userInput.split(" ") request = liste[0] for i in range(1, len(liste)): content += liste[i] if (i != len(liste) - 1): content += " " else: request = userInput content = None self.send_payload(request, content) if request == "logout": self.disconnect() reciever = MessageReceiver(self, self.connection) reciever.daemon = True reciever.start()
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket(AF_INET, SOCK_STREAM) # TODO: Finish init process with necessary code # START self.host = host self.server_port = server_port # Flyttet opp hit fra run self.connection.connect((self.host, self.server_port)) # Lage en tråd # Trenger vi self. forran? thread = MessageReceiver(self, self.connection) # Starter tråden thread.start() self.parser = MessageParser() # Motta input fra bruker while True: user_input = raw_input() if (user_input != None) & (len(user_input) >= 1): # Stopper while løkka # if (user_input.startswith("logout")): # self.send_payload(user_input) # break; # else: self.send_payload(user_input)
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.host = host self.server_port = server_port self.run() # Start a MessageReceiver thread receiver = MessageReceiver(self, self.connection) receiver.start() # Create a MessageParser object for use later self.parser = MessageParser() # Loop to handle continuously reading from input while True: user_input = raw_input() if user_input is not None and user_input is not "": self.send_payload(user_input)
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.run() receiver = MessageReceiver(self, self.connection) receiver.start() while alive: msg = raw_input() msg = msg.split() request = msg[0] if len(msg) == 2: content = msg[1] else: content = None payload = json.dumps({'request': request, 'content': content}) self.send_payload(payload) receiver.join() self.disconnect()
def run(self): try: # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) messageReceiver = MessageReceiver(self, self.connection) messageReceiver.start() except socket.error as e: sys.exit("Connection to server refused.") while (not self.connection._closed): if self.state == State.LOGIN: print("Username:"******"Disconnected from server")
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.host = host self.server_port = server_port self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connect() self.messagereceiver = MessageReceiver("client", self.connection) self.messagereceiver.start() self.run() def run(self): while True: try: msg = self.prompt_user() self.send_request( bytes(jsonify(msg), 'utf-8') ) except Exception: print("Exception in client. Restarting client.") traceback.print_exc() return self def connect(self): while True: errno = self.connection.connect_ex((self.host, self.server_port)) if errno == 0: print("Connected to server.") return else: print("Connection failed. Retrying...") sleep(1) def prompt_user(self): msg = {} inp = input() print("\033[1A\033[K", end='') args = inp.split() if len(args) is not 0: msg['request'] = args[0] msg['content'] = "" if len(args)>1: msg['content'] = inp[len(args[0])+1:] return msg else: msg["content"] = "" msg["request"] = "" return msg def send_request(self, request): self.connection.send(request)
def run(self): # Initiate the connection to the server s_thread = MessageReceiver(self, self.connection) s_thread.daemon = True s_thread.start() while self.active: self.get_input()
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.host = host self.server_port = server_port self.messageParser = MessageParser() self.messageReceiver = MessageReceiver(self, self.connection) self.run() def run(self): """ Main process of the client. Waits for input from user """ self.connection.connect((self.host, self.server_port)) self.messageReceiver.start() print 'Client running...\nType \'quit\' to end or \'help\' for info' while True: command = raw_input() if command == 'quit': self.disconnect() print 'Client closing' break self.send_payload(self.messageParser.parse_dataToSend(command)) def disconnect(self): """ Close sock connection """ self.connection.close() def receive_message(self, message): """ Prints received message after it's parsed """ print self.messageParser.parse(message) def send_payload(self, data): """ Sends data to server """ self.connection.send(data)
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) # print "[*] Kobling etablert" listener = MessageReceiver(self, self.connection) listener.daemon = True listener.start() # print "[*] Lytter startet." self.handle_input()
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) print "[*] Kobling etablert" lytter = MessageReceiver(self,self.connection) lytter.daemon = True lytter.start() print "[*] Lytter startet." self.handle_input()
class Client: """ This is the chat client class """ # Set to True if you wish to exit the chat client exit = False def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_address = (host, server_port) # Initiate the message parser class self.client_message_parser = ClientMessageParser() self.message_sender_thread = MessageSender self.message_receiver_thread = MessageReceiver self.run() def run(self): # Initiate the connection to the server self.connection.connect(self.server_address) # Instantiate the message receiver class as a new thread and start the thread self.message_receiver_thread = MessageReceiver(self, self.connection) self.message_receiver_thread.start() # Instantiate the message sender class as a new thread and start the thread self.message_sender_thread = MessageSender(self, self.connection) self.message_sender_thread.start() # Run until the user sets exit to False try: while not self.exit: payload = raw_input("") print "\n" if payload == 'exit': self.exit = True break elif self.input_is_valid(payload): encoded_message = self.client_message_parser.parse_user_input(payload) self.message_sender_thread.queue_payload_for_sending(encoded_message) finally: # Have to wait for the logout message to actually be sent self.disconnect() print "Disconnected from server." def disconnect(self): self.connection.close() def input_is_valid(self, payload): return not len(payload.strip()) == 0
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ self.host = host self.server_port = server_port # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.receiver = MessageReceiver(self, self.connection) self.receiver.start() def login(self, username): payload = json.dumps({"request": "login", "content": username}) self.send_payload(payload) def logout(self): payload = json.dumps({"request": "logout"}) self.send_payload(payload) def send_msg(self, msg): payload = json.dumps({"request": "msg", "content": msg}) self.send_payload(payload) def send_names_request(self): payload = json.dumps({"request": "names"}) self.send_payload(payload) def send_help_request(self): payload = json.dumps({"request": "help"}) self.send_payload(payload) def disconnect(self): self.logout() # Close Connection? def receive_message(self, message): # TODO: Handle incoming message print message def send_payload(self, data): self.connection.send(data)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ self.serverport = server_port self.h = host # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.MParser = MessageParser() self.MReceiver = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.h, self.serverport)) self.MReceiver.start() while True: userInput = raw_input() try: if userInput: request, content = userInput.split() if not content: content = None payload = { 'request': request, 'content': content } self.send_payload(payload) except KeyboardInterrupt: self.disconnect() def handleInput(self, userInput): message = userInput.split(' ') def disconnect(self): self.connection.close() print "Server disconnected." def receive_message(self, message): print self.MParser.parse(message) def send_payload(self, data): payload = json.dumps(data) self.connection.send(payload)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.userLoggedIn = False self.messageReceiver = MessageReceiver( self, self.connection) # is a thread by itself. self.userInput = UserInput(self) # is a thread by itself. self.parser = MessageParser(self) self.run() def run(self): # Initiate the connection to the server try: self.connection.connect((self.host, self.server_port)) except: print "No connection to the server were established. Exiting." sys.exit() self.messageReceiver.start() # start the thread self.userInput.start() # start the thread print "Client Ready. Please type command. type 'help' to view server commands." def disconnect(self): self.connection.close() print "Server disconnected" self.userInput.kill() sys.exit() pass def receive_message(self, message): parsed_message = self.parser.parse(message) print parsed_message def send_payload(self, data): json = self.parser.encode(data) self.connection.send(json) pass
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.messageParser = MessageParser() self.host = "" self.server_port = 9998 # TODO: Finish init process with necessary code self.run() self.messageReceiver = MessageReceiver(self,self.connection) self.messageReceiver.start() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) def disconnect(self): self.messageReceiver.send_disconnect() self.connection.close() quit() def receive_message(self, message): self.messageParser.parse(self.printer, message) def printer(self,time,sender,message_type,message): melding = ("\n[" + time +" : " + message_type + "] " + sender+ ": " + message + "\n>>> ") print melding def send_payload(self, data): if data == "getHistory": self.messageReceiver.getHistory() elif data == "getNames": self.messageReceiver.getNames() elif data == "getHelp": self.messageReceiver.getHelp() else: self.messageReceiver.sendMessage(data) def login(self, data): brukerNavn = self.messageParser.parse_login(data) self.messageReceiver.send_login(brukerNavn)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.userLoggedIn = False self.messageReceiver = MessageReceiver(self, self.connection) # is a thread by itself. self.userInput = UserInput(self) # is a thread by itself. self.parser = MessageParser(self) self.run() def run(self): # Initiate the connection to the server try: self.connection.connect((self.host, self.server_port)) except: print "No connection to the server were established. Exiting." sys.exit() self.messageReceiver.start() # start the thread self.userInput.start() # start the thread print "Client Ready. Please type command. type 'help' to view server commands." def disconnect(self): self.connection.close() print "Server disconnected" self.userInput.kill() sys.exit() pass def receive_message(self, message): parsed_message = self.parser.parse(message) print parsed_message def send_payload(self, data): json = self.parser.encode(data) self.connection.send(json) pass
def run(self): self.connection.connect((self.host, self.server_port)) message_receiver = MessageReceiver(self, self.connection) message_receiver.start() while True: message = raw_input('Enter command \n') self.send_payload(message) if message == 'logout': time.sleep(1) break self.disconnect()
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) worker = MessageReceiver(self, self.connection) worker.daemon = True worker.start() running = True while running: raw = raw_input() if raw == "exit": running = False self.disconnect() else: self.send_payload(raw)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.MessageReceiver = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.MessageReceiver.start() while True: data = raw_input("") if data == 'exit': self.disconnect() sys.exit() self.send_payload(str(data)) def disconnect(self): self.send_payload(json.dumps({'request': 'logout'})) self.connection.close() def send_payload(self, data): splitted = data.split(" ") if data.find('help') != -1 or data.find('names') != -1 or data.find( 'history') != -1 or data.find('logout') != -1: self.connection.sendall(json.dumps({'request': splitted[0]})) elif data.find('login') != -1: self.connection.sendall( json.dumps({ 'request': splitted[0], 'content': splitted[1] })) else: self.connection.sendall( json.dumps({ 'request': 'msg', 'content': data }))
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.chat = None self.run() msgRecv = MessageReceiver(self, self.connection) msgRecv.start()
def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) adress = ('localhost', 9998) self.connection.connect(adress) receiver = MessageReceiver(self, self.connection) receiver.start() self.running = True self.run()
class Client: def __init__(self, host, server_port): self.host = host self.server_port = server_port """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.start() while (1): new_payload = self.take_input() if new_payload['request'] == 'disconnect': self.disconnect() exit() self.send_payload(json.dumps(new_payload)) time.sleep(0.1) def disconnect(self): self.connection.close() def receive_message(self, message): msg_parser = MessageParser() print msg_parser.parse(message) def send_payload(self, data): self.connection.send(data) def take_input(self): payload = {} payload['request'] = raw_input() if payload['request'] == 'login' or payload['request'] == 'msg': payload['content'] = raw_input('Enter content:') print '\n' return payload
def run(self): print "Type 'help' if stuck" self.connection.connect((self.host, self.server_port)) thread1 = MessageReceiver(self, self.connection) thread1.start() while True: self.data = raw_input(">>> ") print "\033[A \033[A" # shit starts here # print self.data i = 0 if self.data == "help": print "HELP\n---------------\n\nlogin <username> ------ log in with the given username\n" \ "logout -------- log out \nmsg <message> ------ send message \nnames ------- list users in chat" \ "\nhelp ------- view help text " continue elif self.data[:5] == "login": # make this a login message i = 6 self.jdata['request'] = "login" elif self.data[:6] == "logout": # make this a logout message i = 7 self.jdata['request'] = "logout" elif self.data[:3] == "msg": # this is a message i = 4 self.jdata['request'] = "msg" elif self.data[:5] == "names": # client asks for names i = 6 self.jdata['request'] = "names" elif self.data[:7] == "history": # client asks for names i = 8 self.jdata['request'] = "history" else: print "ERROR - no command was recognised" continue # shit ends here (probably not) self.jdata['content'] = self.data[i:] #strip it json_data = json.dumps(self.jdata) # print "JSON to be sent: " + json_data # print json.dumps(json_data, indent=4, sort_keys=True) self.connection.sendall(json_data) # + "\n") # self.received = self.connection.recv(1024) # v2 # print self.received self.disconnect()
def run(self): # Initiate the connection to the server self.connection.connect((self.server_host, self.server_port)) # We kick off a background thread which'll listen for incoming messages from # the server. Whenever a message from the server is received, the MessageReceiver # will call the receive_message method in this class. thread = MessageReceiver(self, self.connection) thread.start() # We listen for user input and send it to the dispatcher for formatting. while True: input_string = str(input("")) self.dispatcher(input_string)
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.msgParser = MessageParser() msgReceiver = MessageReceiver(self, self.connection) msgReceiver.start() print("INSTRUCTIONS\nUser must login first - type 'login <username>'\ntype 'help' for list over available commands\n\n") while self.connection: userinput = raw_input() if userinput == 'logout': self.disconnect() elif userinput == 'exit': exit() else: self.send_payload(userinput)
def run(self): # TODO # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) receiver = MessageReceiver(self, self.connection) receiver.start() running = True while running: print("What to do: ") client_input = input() if client_input == "exit": running = False self.disconnect() else: self.send_payload(client_input)
class Client: def __init__(self, host, server_port): # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.run() self.msg = '' def run(self): # Connecting to server self.connection.connect((self.host, self.server_port)) #Creats the running thread for recieving messages self.thread = MessageReceiver(self, self.connection) self.thread.start() #--> run in MessageReceiver running_status = self.thread.is_alive() while running_status: #Collects input from chat-user user_input = raw_input().split(' ', 1 ) request = user_input[0] content = 'None' try: content = user_input[1] except Exception, e: pass if request == 'login': try: content = user_input[1] except Exception, e: print '[ERROR] Username unvalid. Try another username with the allowed characters: A-Z, a-z, 0-9' pass payload = json.dumps({'request': 'login', 'content': content}) self.send_payload(payload) elif request == 'logout': payload = json.dumps({'request': 'logout', content: None}) self.send_payload(payload)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.messageReceiver = MessageReceiver(self, self.connection) self.run() # TODO: Finish init process with necessary code def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.messageReceiver.start() print 'Welcome to this chatting room! Start chatting by using command login <username>' while True: input = raw_input('>') self.send_payload(input) def disconnect(self): # TODO: Handle disconnection self.connection.disconnect() def receive_message(self, message): # TODO: Handle incoming message1 print(message) def send_payload(self, data): # TODO: Handle sending of a payload stringarray = data.split(' ') content = "" for i in range(1, len(stringarray)): content += stringarray[i] content += ' ' data = {'request': stringarray[0], 'content': content} self.connection.sendall(json.dumps(data))
def run(self): # Initiate the connection to the server print 'Connecting to the server..' self.connection.connect((self.host, self.server_port)) # Initialize a message reciver reciver = MessageReceiver(self, self.connection) reciver.start() # Wait a second for server response time.sleep(1) cin = str(raw_input()) while cin != "exit": temp_dict = cin.partition(' ') payload = {"request": temp_dict[0], "content": temp_dict[2]} self.send_payload(json.dumps(payload)) cin = str(raw_input()) self.disconnect()
class Client: def __init__(self, host, server_port): self.host = host self.server_port = server_port self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.run() def run(self): self.connection.connect((self.host, self.server_port)) self.messagereceiver = MessageReceiver(self, self.connection) self.messagereceiver.start() def disconnect(self): self.messagereceiver.is_running = False self.connection.close() pass def send_payload(self, data): self.connection.send(data.encode("UTF-8")) pass
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) receiver = MessageReceiver(self, self.connection) receiver.start() while True: command = input("> ") if len(command.split(" ")) > 1: # It's a command with content command = command.split(" ") if command[0] == "login": raw_message = { 'request': 'login', 'content': command[1] } elif command[0] == "msg": messageString = "" for i in command[1:]: messageString += i + ' ' messageString = messageString[:-1] raw_message = { 'request': 'msg', 'content': messageString } else: print("Unknown command! Please try again.") continue else: # It's a command without content if command == 'logout' or command == 'help' or command == 'history' or command == 'names': raw_message = { 'request': command, 'content': None } else: print("Unknown command! Please try again.") continue JSON_message = json.dumps(raw_message) self.send_payload(JSON_message.encode("utf-8"))
def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) receiver=MessageReceiver(self, self.connection) receiver.start() print("Hello and welcome to a highly functional chat service") print("Type 'help' for help") while (1): userInput = input() try: request, content = userInput.split(' ', 1) except (ValueError, KeyboardInterrupt, IndexError): content = None request = userInput payload = {'request': request.lower(), 'content': content} self.send_payload(payload) if (payload['request']=='logout'): sleep(0.5) self.disconnect()
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.host = host self.server_port = server_port self.receiver = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.receiver.start() print '-- WELCOME TO CHAT --' print 'Type <help> for useful commands.' while True: rawInput = raw_input() if rawInput: try: request, content = rawInput.split(" ", 1) except ValueError, KeyboardInterrupt: request = rawInput content = '' payload = {'request': request.lower(), 'content': content} self.send_payload(payload) if request == 'logout': sleep(0.5) # Wait for server info self.disconnect()
class Client: def __init__(self, host, server_port): self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.msgRecTask = MessageReceiver(self, self.connection) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.msgRecTask.start() self.userName = "******" self.loggedOn = False print bcolors.OKBLUE + ( "Welcome to this chat client - type \"-login\" to log on" ) + bcolors.ENDC while True: userInput = raw_input(":") if userInput == "-login": # self.connection.settimeout(0.5) # try: # testRecieve=self.connection.recv(4096) # print testRecieve # if testRecieve=="": # self.connection.connect((self.host,self.server_port)) # except socket.timeout: # self.connection.settimeout(None) # print("timeout") # except: # self.connection.settimeout(None) # print("Tried to recoonect, failed") # self.connection.settimeout(None) userName = raw_input("Username: "******"request": "login", "content": userName.encode()} try: payload = json.dumps(data) self.send_payload(payload) self.loggedOn = True except: print("Error while logging on") #self.msgRecTask.stop() #self.msgRecTask.start() elif userInput == "-logout" and self.loggedOn: print("Got here") payload = json.dumps({ "request": "logout", "content": self.userName }) self.send_payload(payload) self.loggedOn = False self.disconnect() print("Succesfully logged out\n") elif userInput == "-help": payload = json.dumps({"request": "help", "content": ""}) self.send_payload(payload) elif userInput == "-history" and self.loggedOn: payload = json.dumps({"request": "history", "content": ""}) self.send_payload(payload) elif userInput == "-names" and self.loggedOn: payload = json.dumps({"request": "names", "content": ""}) self.send_payload(payload) else: if self.loggedOn: data = {"request": "msg", "content": userInput} try: payload = json.dumps(data) self.send_payload(payload) except: print("Error while sending msg") continue else: print("Invalid operation, consider logging in") def disconnect(self): self.connection.close() def receive_message(self, message): print(message) def send_payload(self, data): self.connection.send(data)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.run() def disconnect(self): self.receiver.close() sleep(0.1) self.connection.close() print("Disconnecting") def receive_message(self, payload): try: #print("I got the payload!", payload) # json string payload = json.loads(payload) res = payload['response'] # the response content = payload['content'] #the content timestamp = payload['timestamp'] #the timestamp if res == "history": history = "" for client in content: history += "<" + client['timestamp'] + "> " + client[ 'sender'] + ": " + client['content'] + "\n" print("History:\n" + history) elif res == "names": print("<" + timestamp + "> " + content) elif res == "help": print("<" + timestamp + "> \n" + content) elif res == "message": print("<" + timestamp + "> " + payload['sender'] + ": " + content) elif res == "logout": print("<" + timestamp + "> " + content) else: print("<" + timestamp + "> " + content) except Exception as e: print(e) def send_payload(self, data): try: self.connection.send(data.encode()) # gjør string til binært except Exception as e: print("failed to send payload") print(e) def msg(self, payload): self.send_payload(json.dumps({"request": "msg", "content": payload})) def helptext(self): self.send_payload(json.dumps({"request": "help", "content": None})) def logout(self): self.send_payload(json.dumps({"request": "logout", "content": None})) def login(self, payload): self.send_payload(json.dumps({"request": "login", "content": payload})) def names(self): self.send_payload(json.dumps({"request": "names", "content": None})) def history(self): self.send_payload(json.dumps({"request": "history", "content": None})) def run(self): # Initiate the connection to the server try: self.connection.connect((self.host, self.server_port)) print("connected") except Exception as i: print(i) print("Could not connect to host") exit() # Start messageParser self.parser = MessageParser() # Start messageReceiver self.receiver = MessageReceiver(self, self.connection) self.receiver.start() print("messageRec OK") while True: print("Write 'help' for list of commands.") userIn = input(">>> ") if userIn == "msg": message = input("Write your message: ") self.msg(message) elif userIn == "login": username = input("Username: "******"logout": self.logout() elif userIn == "names": self.names() elif userIn == "history": self.history() elif userIn == "help": self.helptext() elif userIn == "color": colors = ["red", "blue", "cyan", "green", "yellow", "pink"] colorCodes = [ '\033[91m', '\033[94m', '\033[96m', '\033[92m', '\033[93m', '\033[95m' ] print("List of colors:\n- " + bcolors.OKGREEN + "green" + bcolors.ENDC + "\n- " + bcolors.OKBLUE + "blue" + bcolors.ENDC + "\n- " + bcolors.OKRED + "red" + bcolors.ENDC + "\n- " + bcolors.PINK + "pink" + bcolors.ENDC + "\n- " + bcolors.YELLOW + "yellow" + bcolors.ENDC + "\n- " + bcolors.CYAN + "cyan" + bcolors.ENDC) userColor = input("What color do you want? ") if userColor in colors: for i in range(len(colors)): if (userColor == colors[i]): self.color = colorCodes[i] else: print("Not a supported color...") elif userIn == "colors": print( "\nTo be implemented; paint your username with following colors:" ) print(bcolors.OKGREEN + "green" + bcolors.ENDC) print(bcolors.OKBLUE + "blue" + bcolors.ENDC) print(bcolors.PINK + "pink" + bcolors.ENDC) print(bcolors.CYAN + "cyan" + bcolors.ENDC) print(bcolors.OKRED + "red" + bcolors.ENDC) print(bcolors.YELLOW + "yellow" + bcolors.ENDC) else: print("Not recognized command.") continue
def receive_message(self, message): # TODO: Handle incoming message msg_receiver = MessageReceiver(client, self.connection) msg_receiver.start()
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ############## QT ################# self.host = host self.server_port = server_port self.run() ################################### #Shiv def run(self): self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.daemon=True self.thread.start() while True: input_= raw_input('>> ') self.send_payload(input_) if input_== 'quit': break self.disconnect() #Shiv def disconnect(self): self.thread.stop = True self.connection.close() #Shiv def receive_message(self, message): #Decode message msg_parser = MessageParser() #print(message) #if message is None: # print('oops its none') decoded_message = msg_parser.parse(message) #Print the "handled" response print(decoded_message) #Shiv def send_payload(self, data): if(data.startswith('login')): try: username=data.split()[1] except IndexError: username='' payload = {'request': 'login', 'content': username} elif(data.startswith('logout')): payload = {'request': 'logout', 'content': None} elif(data.startswith('msg')): data = data.split() dummy = data.pop(0) content = '' if not data: payload = {'request': 'msg', 'content': ''} else: for element in data: content += element +' ' payload = {'request': 'msg', 'content': content} elif(data.startswith('names')): payload = {'request': 'names', 'content': None} elif(data.startswith('help')): payload = {'request': 'help', 'content': None} elif(data.startswith('history')): payload = {'request': 'history', 'content':None} else: payload = {'request': '', 'content': None} self.connection.sendall(json.dumps(payload))
class Client: legal_methods = [ 'login <username>', 'logout', 'msg <message>', 'history', 'names', 'help' ] program_die = False """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ self.host = host self.server_port = server_port self.logger = Logger(None) self.parser = MessageParser() # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.run() def run(self): self.logger.message(""" \033[94m///////////////////////////////////////\033[0m \033[94m// SLACK v2.0 //\033[0m \033[94m//\033[0m Just like slack, only better! \033[94m//\033[0m \033[94m///////////////////////////////////////\033[0m """) # Initiate the connection to the server try: self.connect() self.logger.success({ 'title': 'Connected to Chat', 'message': 'Successfully connected to chat on address: {}:{}'.format( self.host, self.server_port) }) except Exception as e: self.logger.error({'title': 'Connection Error', 'message': e}) self.logger.message('\nExiting program\n') sys.exit(1) # N.B. This HAVE TO be after Socket has connected (ref. line 32) self.message_receiver = MessageReceiver(self, self.connection) self.message_receiver.start() while True: self.logger.message("Type 'help' for help") try: action = input('> ') except KeyboardInterrupt as keyey: self.send_payload(self.logout()) break # Kills the program if this is set to true if self.program_die: break method = None # Stores the selected methods if action == 'login': method = self.login elif action == 'logout': method = self.logout elif action == 'names': method = self.names elif action == 'history': method = self.history elif action == 'msg': method = self.msg elif action == 'help': method = self.help else: self.logger.error({ 'title': 'Illegal action', 'message': 'action: {}'.format(action) }) continue try: self.send_payload(method()) except Exception as e: self.logger.error({'title': 'Sending Error', 'message': e}) def connect(self): """ Centralizes the connection process """ try: self.connection.connect((self.host, self.server_port)) except ConnectionRefusedError as e: raise ConnectionError( 'Could not connect to server at {}:{}'.format( self.host, self.server_port)) def disconnect(self): # TODO: Handle disconnection self.logger.message({'title': 'Logged Out', 'message': 'Bye\n'}) sys.exit(0) def receive_message(self, message): if message == 'DIE': self.logger.message('\nShutting down\n[press enter to exit]') self.program_die = True # Shuts the program down in the program-loop sys.exit( 0 ) # Stops the thread (Remove and you'll get an segmentation fault) try: print("") self.logger.message(self.parser.parse(message)) except ParseException as e: # Use parse error to forward errors from the parser self.logger.error({ 'title': e.args[1], 'message': e.args[0] } if len(e.args) > 1 else str(e)) print('\n>', end=" ") # Quick fix, so that the user knows what to see def send_payload(self, data): payload = json.dumps(data).encode() self.connection.sendall(payload) if data['request'] == 'logout': self.disconnect() def login(self): user = input('username > ') return {'request': 'login', 'content': user} def logout(self): return {'request': 'logout'} def names(self): return {'request': 'names'} def history(self): return {'request': 'history'} def msg(self): msg = input('message > ') return {'request': 'msg', 'content': msg} def help(self): return {'request': 'help'}
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host; self.port = server_port; # TODO: Finish init process with necessary code self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.port)) self.connected = True self.msg_parser = MessageParser() self.msg_receiver = MessageReceiver(self, self.connection) self.msg_receiver.start() while self.connected: inp = raw_input("command <content>:\n").split() command = inp[0] if command not in legal_requests: print("please type a legal command") continue content = None if command == 'login' or command == 'msg': if len(inp) <= 1: print("please type <content>") continue content = " ".join(inp[1:]) data = { 'request': command, 'content': content} self.send_payload(json.dumps(data)) self.msg_receiver.join() def disconnect(self): print("disconnected from server") self.connected = False def receive_message(self, message): message = self.msg_parser.parse(message) try: response = message['response'] content = message['content'] except: print "error" print message return if response == 'error': print content elif response == 'history': for chat_entry in content: print(chat_entry['sender'] + ":" + chat_entry['content']) elif response == 'message': sender = message['sender'] print sender + ":" + content elif response == 'info': print content else: print "wops" + message def send_payload(self, data): self.connection.sendto(data, (self.host, self.port))
class Client(): """ This is the chat client class """ terminal_width = 80#windows width, maybe implement a check for unix terminals? nah! help_text="""== Using the client: == If the prompt says "Username: "******"msg: ", which means you can start chatting away. == Commands: == The client supports a few commands: /help: displays this help text /logout or /exit: logs out from the server and disconnects /names or /who: Queries the server for a list of who is present on the server. /shelp: Queries the server for its help text. """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ self.host = (host, server_port) # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Set up the incoming messages queue: self.queue = Queue() self.prompt = ["username: "******"Welome to our totally awesome chat client!") self.print_message("If you need help with using the client, type /help") self.print_message("If you need help with using the server, type /shelp") self.print_message("Connecting to %s:%s..." % self.host) self.print_message("") self.prompt[0] = "Username: "******"Please select a username to go by:") while 1: out = self.handle_input() if out: if out[0] == "/":#commands: command = out[1:].split(" ")[0] if command == "help": self.print_message(self.help_text) elif command == "logout" and mode==1: self.send_logout() self.disconnect() elif command == "exit": self.send_logout() elif command == "names" and mode==1: self.send_names() elif command == "who" and mode==1: self.send_names() elif command == "shelp": self.send_help() else: self.print_message("Unknown command \"/%s\"" % command) elif mode == 0:#username self.send_login(out) self.print_message("logging in as %s..." % out) else:#message self.send_msg(out) pass#server should echo the message if not self.queue.empty(): data = self.queue.get() response, timestamp, sender, content = self.MessageParser.parse(data) self.queue.task_done()#neccesary? nah... if response.lower() in ("error", "info"): if response.lower() == "info" and ("success" in content.lower() or "logged in" in content.lower()): mode = 1 self.prompt[0] = "msg: " #self.refresh_prompt()#is handeled in the print below instead self.print_message("%s: %s" % (response, content)) elif response.lower() == "message": self.print_message("%s: %s" % (sender, content)) elif response.lower() == "history": if not type(content) is list: content = json.loads(content) for i in content: try: i = json.loads(i) except TypeError: pass if i["response"].lower() == "message": self.print_message("%s: %s" % (i["sender"], i["content"])) #run() helpers: def handle_input(self):#call each iteration, handles user input, returns a string if enter is pressed: char = GetChar() if char: if char == "\n": ret = "".join(self.prompt[1]) self.prompt[1] = [] self.refresh_prompt() return ret elif char == "\b": if self.prompt[1]: self.prompt[1].pop(-1) else: self.prompt[1].append(char) self.refresh_prompt() def print_message(self, string): #clear sys.stdout.write("\r%s\r" % (" "*(self.terminal_width-1))) #print print string #recreate prompt: self.refresh_prompt(clear=False) def refresh_prompt(self, clear=True): #clear if clear: sys.stdout.write("\r%s\r" % (" "*(self.terminal_width-1))) #recreate prompt: sys.stdout.write(self.prompt[0] + ("".join(self.prompt[1]))[-self.terminal_width+1+len(self.prompt[0]):]) def send_login(self, username): out = {"request":"login"} out["content"] = username self.send_payload(json.dumps(out)) def send_msg(self, message): out = {"request":"msg"} out["content"] = message self.send_payload(json.dumps(out)) def send_logout(self):#todo: also handle disconnecting out = {"request":"logout"} out["content"] = None self.send_payload(json.dumps(out)) def send_names(self):#ask for a list of users out = {"request":"names"} out["content"] = None self.send_payload(json.dumps(out)) def send_help(self):#ask server for help out = {"request":"help"} out["content"] = None self.send_payload(json.dumps(out)) #events: def disconnect(self): self.connection.close() sys.exit(0) def receive_message(self, message):#works with threads self.queue.put(message, True, None)#2threadingsafe4u def send_payload(self, data): self.connection.send(data)#2ez4u
self.e.pack(expand=True, fill=tkinter.X); self.gui.mainloop(); while True: inp = input(">> "); self.send_message(inp); def receive_message(self, message): self.t.configure(state="normal"); self.t.insert('end', MessageParser.parse(json.loads(message)) + "\n"); self.t.configure(state="disabled"); #print(MessageParser.parse(json.loads(message))); def send_payload(self, data): self.connection.send(data); if __name__ == '__main__': """ This is the main method and is executed when you type "python Client.py" in your terminal. No alterations are necessary """ client = Client(input(), 9998); reqHandler = MessageReceiver(client,client.connection); reqHandler.start(); client.run();
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.host = host self.server_port = server_port self.run() self.msg = '' def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.start() thread_running = self.thread.is_alive() while thread_running: #print "You are connected to the server. Use login,logout,msg,names,help" user_input = raw_input().split(' ', 1) request = user_input[0] content = 'None' try: content = user_input[1] except Exception, e: # ? pass if request == "login": print "Your request was login" payload = json.dumps({'request': 'login', 'content': content}) self.send_payload(payload) #print payload elif request == "logout": payload = json.dumps({'request': 'logout', 'content': None}) self.send_payload(payload) elif request == "msg": payload = json.dumps({'request': 'msg', 'content': content}) self.send_payload(payload) elif request == "names": payload = json.dumps({'request': 'names', 'content': None}) self.send_payload(payload) elif request == "help": payload = json.dumps({'request': 'help', 'content': None}) self.send_payload(payload) pass
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port # TODO: Finish init process with necessary code self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.start() while True: time.sleep(0.5) request_content = input("Type in your request:").split(' ', 1) try: request_content[0] = request_content[0].lower() request_content[1] = request_content[1].lower() print(request_content) if request_content[1] == "none": if request_content[0] == "names": self.send_payload({ "request": "names", "content": "None" }) elif request_content[0] == "help": self.send_payload({ "request": "help", "content": "None" }) else: if request_content[0] == "logout": self.disconnect() elif request_content[0] == "names": self.send_payload({ "request": "names", "content": "None" }) elif request_content[0] == "help": self.send_payload({ "request": "help", "content": "None" }) elif request_content[0] == "login": self.send_payload({ "request": "login", "content": request_content[1] }) elif request_content[0] == "msg": self.send_payload({ "request": "msg", "content": request_content[1] }) else: self.not_supported(request_content) except IndexError: print("Input not valid!") def disconnect(self): payload = {"request": "logout", "content": "None"} self.send_payload(payload) def receive_message(self, message): message_parser = MessageParser() print(message_parser.parse(message)) def send_payload(self, data): temp_data = json.dumps(data) self.connection.send(temp_data.encode()) def not_supported(self, request_content): print("The following request and/or content: " + request_content[0] + " and " + request_content[1] + " is not supported.")
class Client: """ This is the chat client class """ host = "localhost" server_port = 9998 def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.msg = MessageReceiver(self, self.connection) self.host = host self.server_port = server_port self.hasLoggedOn = False self.connection.connect((self.host, self.server_port)) #msg is a request sent from the client to the server print("Messager Reciever started") self.msg.start() print("Run method started!") self.run() def run(self): # Initiate the connection to the server print "Welcome to the chat! Type help to get help." while True: incoming = raw_input() if incoming == 'help': helpText = "Type login to log in. Type logout to log out. Type names to get all names." print helpText elif incoming == 'login' and not self.hasLoggedOn: print "Please type your desired username." incoming = raw_input() obj = {"request": "login", "content": incoming} try: jsonobj = json.dumps(obj) except UnicodeDecodeError: print "Invalid characters in username. Please try again." self.send_payload(jsonobj) self.hasLoggedOn = True elif incoming == 'logout' and self.hasLoggedOn: print "Logging out..." obj = {"request": "logout", "content": ""} try: jsonobj = json.dumps(obj) self.send_payload(jsonobj) self.disconnect() except UnicodeDecodeError: print "Invalid characters" continue elif incoming == 'logout' and not self.hasLoggedOn: print "You have to be logged in to log out" elif incoming == 'names' and self.hasLoggedOn: obj = {"request": "names", "content": ""} try: jsonobj = json.dumps(obj) except UnicodeDecodeError: print "Invalid characters" self.send_payload(jsonobj) elif incoming == 'history' and self.hasLoggedOn: self.getHistory() else: if not self.hasLoggedOn: print "You have to be logged on to send a message. Please try again." elif self.hasLoggedOn: obj = {"request": "msg", "content": incoming} try: jsonobj = json.dumps(obj) except UnicodeDecodeError: print "Invalid characters" self.send_payload(jsonobj) def disconnect(self): print "Disconnecting..." self.connection.close() self.hasLoggedOn = False print "You are disconnected." pass def receive_message(self, message): print "Received message:" + message parser = MessageParser() parsedMessage = parser.parse(message) print parsedMessage pass def send_payload(self, data): self.connection.send(data) pass def getHistory(self): obj = {"request": "history", "content": ""} jsonobj = json.dumps(obj) self.send_payload(jsonobj)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.host = host self.server_port = server_port self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.start() while True: text = input().split(' ', 1) if (len(text) > 0 and len(text) < 3): if (len(text) == 1): text.append('') if (text[0] == 'login'): payload = json.dumps({ 'request': 'login', 'content': text[1] }) self.send_payload(payload) elif (text[0] == 'logout'): self.disconnect() elif (text[0] == 'names'): payload = json.dumps({'request': 'names'}) self.send_payload(payload) elif (text[0] == 'help'): payload = json.dumps({'request': 'help'}) self.send_payload(payload) elif (text[0] == 'msg'): payload = json.dumps({ 'request': 'msg', 'content': text[1] }) self.send_payload(payload) else: print('Unknown command, type "help" for help') else: print('Unknown command, type "help" for help') def disconnect(self): payload = json.dumps({'request': 'logout'}) self.send_payload(payload) sys.exit() def receive_message(self, message): recv = message if (recv['response'] == 'info'): print('[Info]', recv['content']) elif (recv['response'] == 'error'): print('[Error]', recv['content']) elif (recv['response'] == 'msg'): print(recv['sender'] + ':', recv['content']) elif (recv['response'] == 'history'): for message in recv['content']: self.receive_message(message) else: print('Unknown server message:', recv) pass def send_payload(self, data): self.connection.send(bytes(data, 'UTF-8'))
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ self.loggedon = False # Set up the socket connection to the server try: self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as e: print "Failed to create socket. Error message:", e self.host = host self.server_port = server_port self.lastMessageRecieved = None self.parser = MessageParser() self.run() self.rcv = MessageReceiver(self, self.connection) self.rcv.start() def run(self): # Initiate the connection to the server try: self.connection.connect( (self.host, self.server_port)) #Connect to server print 'Successfully connected to the server.' except socket.error as e: #If connection fails print "Failed to connect to server. \nError message:", e def disconnect(self): try: self.connection.close() self.loggedon = False exit() except socket.error as e: print "Failed to disconnect from server. Error message:", e pass def receive_message(self, message): self.lastMessageRecieved = self.parser.parse(message) if self.lastMessageRecieved == 'error': self.loggedon = False def send_payload(self, data): #Def the different responses if data == 'help': payload = {'request': 'help', 'content': None} elif data == None: return 0 elif data == 'names': payload = {'request': 'names', 'content': None} elif data == 'logout': payload = {'request': 'logout', 'content': None} self.loggedon = False elif data == 'disconnect': return 0 else: if self.loggedon == False: payload = {'request': 'login', 'content': data} self.loggedon = True else: payload = {'request': 'msg', 'content': data} self.connection.send(json.dumps(payload)) return 1
class Client: """ This is the chat client class """ host = "" server_port = 0 thread = None def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port # TODO: Finish init process with necessary code - I think done, maybe? self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) # Sets up a unique thread self.thread = MessageReceiver(self, self.connection) # Start listening for messages self.thread.start() # Listen for and respond to input while True: inputvalue = raw_input().split(' ', 1) action = inputvalue[0] # command might only be 1 word try: content = inputvalue[1] except Exception as e: pass if action == 'login': if self.thread.isActive is False: print('Re-Run the program to reconnect.') return payload = json.dumps({'request': 'login', 'content': content}) self.send_payload(payload) elif action == 'logout': payload = json.dumps({'request': 'logout'}) self.send_payload(payload) self.disconnect() print('disconnected') elif action == 'names': payload = json.dumps({'request': 'names'}) self.send_payload(payload) elif action == 'help': payload = json.dumps({'request': 'help'}) self.send_payload(payload) elif action == 'msg': payload = json.dumps({'request': 'msg', 'content': content}) self.send_payload(payload) elif action == 'history': payload = json.dumps({'request': 'history'}) self.send_payload(payload) else: print('Unknown command, type "help" for help') def disconnect(self): self.connection.close() self.thread.isActive = False # Now it will not be possible to reconnect without re-running. pass def receive_message(self, message): # If there is no readable value just ignore try: message = json.loads(message) except Exception as e: return if message['response'] == 'msg': print message['sender'] + ':', message['content'] elif message['response'] == 'info': print '[INFO]', message['content'] elif message['response'] == 'err': print '[ERROR]', message['content'] def send_payload(self, data): # Assuming data is now formatted as JSON # Send TCP Header self.connection.send(data) pass
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = host self.server_port = server_port self.msgRec = MessageReceiver(self,self.connection) self.hasLoggedOn = False self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.msgRec.start() print "Velkommen til denne chatte-appen. Skriv <-login> hvis du vil logge inn. Hvis du har problemer skriv <-help>" print "" while True: command = raw_input('') if command == "-login": print 'Skriv inn ditt onskede brukernavn' username = raw_input('') data = {"request":"login","content":username} try: package = json.dumps(data) self.send_payload(package) self.hasLoggedOn = True except UnicodeDecodeError: print("Ikke bruk norske bokstaver.") continue elif command == "-help":#skal faa hjelpemelding fra server data = {"request":"help","content":""} package = json.dumps(data) self.send_payload(package) elif command == "-names" and self.hasLoggedOn: #faa navn fra server data = {"request":"names","content":""} package = json.dumps(data) self.send_payload(package) elif command == "-logout" and self.hasLoggedOn: data = {"request":"logout","content":username} package = json.dumps(data) self.send_payload(package) self.disconnect() self.hasLoggedOn = False print "Du er naa logget ut" elif command == "-history" and self.hasLoggedOn: #faa historie fra serveren data = {"request":"history","content":""} package = json.dumps(data) self.send_payload(package) else: if self.hasLoggedOn: data = {"request":"msg","content":command} try: package = json.dumps(data) self.send_payload(package) except UnicodeDecodeError: print("Ikke bruk norske bokstaver.") continue else: print "Du maa vaere logget inn for aa gjore det" def disconnect(self): # TODO: Handle disconnection self.connection.close() def receive_message(self, message): # TODO: Handle incoming message if type(message) != str: received_string = self.connection.recv(4096) try: jsonRec = json.loads(received_string) timestamp = jsonRec["timestamp"] sender = jsonRec["sender"] response = jsonRec["response"] content = jsonRec["content"] except ValueError: print("Not JSON-Object, trying again.") elif message: jsonRec = json.loads(message) timestamp = jsonRec["timestamp"] sender = jsonRec["sender"] response = jsonRec["response"] content = jsonRec["content"] if response == "message": msg = "[" + timestamp + " " + sender + "] " + content print msg elif response == "history": msg = "[" + timestamp + " " + sender + "] " + content print msg else: print content # elif response == "error": # print content def send_payload(self, data): # TODO: Handle sending of a payload self.connection.send(data)
class Client: """ This is the chat client class """ username = "" def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket(AF_INET, SOCK_STREAM) self.host = host self.server_port = server_port self.message_reciever = MessageReceiver(self, self.connection) self.message_parser = MessageParser(self) self.received_answer = True self.is_logged_in = False self.run() def run(self): # Initiate the connection to the server self.connection.connect((self.host, self.server_port)) self.message_reciever.start() while True: self.get_input() def get_input(self): if self.received_answer: inputString = input(">>") parts = inputString.split(" ", 1) request = None content = None if len(parts) == 2: command = parts[0] argument = parts[1] if command == "login": if not self.is_logged_in: request = "login" content = argument else: print("You are already logged in!") return elif command == "msg": request = "msg" content = argument else: command = inputString if command == "logout": request = "logout" elif command == "names": request = "names" elif command == "help": request = "help" if not request: print("Invalid input") else: requestDict = {'request': request, 'content': content} jsonData = json.dumps(requestDict) self.send_payload(jsonData) def disconnect(self): # TODO: Handle disconnection self.connection.close() pass def receive_message(self, message): # TODO: Handle incoming message print(self.message_parser.parse(message)) self.received_answer = True def send_payload(self, data): self.received_answer = False self.connection.sendall(bytes(data, 'utf-8'))
class Client: """ This is the chat client class """ def __init__(self, host, server_port): self.host = host self.server_port = server_port """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.run() # TODO: Finish init process with necessary code def run(self): # Initiate the connection to the server print "client: connecting" self.connection.connect((self.host, self.server_port)) self.thread = MessageReceiver(self, self.connection) self.thread.start() print "client: connected" print "1. login <username>, 2. logout, 3. msg <message>, 4. history, 5. users, 6. help\n" while True: payload = self.create_response() self.send_payload(payload) if input is "logout": self.disconnect() break def disconnect(self): # TODO: Handle disconnection self.connection.shutdown(socket.SHUT_RDWR) self.connection.close() def receive_message(self, message): # TODO: Handle incoming message payload = json.loads(message) response = payload["response"] content = payload["content"] sender = payload["sender"] timestamp = payload["timestamp"] if response == "info": print "[info]: " + content elif response == "error": print "[error]: " + content elif response == "msg": print timestamp[11:16] + "-" + sender + ": " + content elif response == "history": for msg in content: self.receive_message(msg) elif response == "help": print str(content) elif response == "users": print "There are " + str( len(content)) + " users logged in: " + str(content) else: print "Unknown response from server: " + message def send_payload(self, data): # TODO: Handle sending of a payload self.connection.sendall(data) # More methods may be needed! def create_response(self): user_input = raw_input(">>> ").split(" ") if (len(user_input) == 1): json_dic = { "response": user_input[0], #type } else: json_dic = { "response": user_input[0], #type "content": user_input[1], #user msg } return json.dumps(json_dic)
class Client: """ This is the chat client class """ def __init__(self, host, server_port): """ This method is run when creating a new Client object """ # Set up the socket connection to the server self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TODO: Finish init process with necessary code self.host = host self.server_port = server_port self.run() self.msg = '' def run(self): # Kobler til server self.connection.connect((self.host, self.server_port)) #Lager en traad å kjore paa self.thread = MessageReceiver(self, self.connection) #Kjorer traaden self.thread.start() running_status = self.thread.is_alive() while running_status: #Hent input fra bruker user_input = raw_input().split(' ', 1 ) print "Melding fra bruker mottatt " #Sorter keyword og innhold, takler kun 'help', 'names' request = user_input[0] try: content = user_input[1] except Exception, e: pass print "Formatert melding " if request == 'login': print "Login mottatt" payload = json.dumps({'request': 'login', 'content': content}) print "Pakket som json" self.send_payload(payload) print "Sendt med self.send_payload(payload)" elif request == 'logout': payload = json.dumps({'request': 'logout'}) self.send_payload(payload) elif request == 'msg': payload = json.dumps({'request': 'msg', 'content': content}) self.send_payload(payload) elif request == 'names': payload = json.dumps({'request': 'names'}) self.send_payload(payload) elif request == 'help': payload = json.dumps({'request': 'help'}) self.send_payload(payload) else: print "Hva er det du prover paa? " return pass