コード例 #1
0
class MessageReceiver(Thread):
    """
    This is the message receiver class. The class inherits Thread, something that
    is necessary to make the MessageReceiver start a new thread, and it allows
    the chat client to both send and receive messages at the same time
    """

    def __init__(self, client, connection):
        """
        This method is executed when creating a new MessageReceiver object
        """

        # Flag to run thread as a deamon
        
	#self.client=client
        self.connection = connection
        # tODO: Finish initialization of MessageReceiver
        super(MessageReceiver,self).__init__()
       

    def run(self):
        # tODO: Make MessageReceiver receive and handle payloads
        self.MessageParser = MessageParser()
        #s_thread = MessageParser(payload)
        #s_thread.start()
        while True:
            payload = self.connection.recv(4096)
            #print('We now listening for input from server.' + payload)
            self.MessageParser.parse(payload)
コード例 #2
0
ファイル: MessageReceiver.py プロジェクト: daniena/TTM4100
 def run(self):
     MsgParser = MessageParser()
     while True:
         data = (self.connection.recv(8192)).decode()
         if data:
             MsgParser.parse(data)
     pass
コード例 #3
0
ファイル: MessageReceiver.py プロジェクト: Santiario/TTM4100
class MessageReceiver(Thread):
    """
    This is the message receiver class. The class inherits Thread, something that
    is necessary to make the MessageReceiver start a new thread, and it allows
    the chat client to both send and receive messages at the same time
    """

    def __init__(self, client, connection):
        super(MessageReceiver, self).__init__()
        """
        This method is executed when creating a new MessageReceiver object
        """

        # Flag to run thread as a deamon. A deamon is a process that runs in the background.
        self.daemon = True

        self.parser = MessageParser()
        self.client = client
        self.connection = connection
        self.start()

    def run(self):
        while True:
            received_message = self.connection.recv(4096)
            try:
                print self.parser.parse(received_message)
            except:
                pass
コード例 #4
0
ファイル: MessageReceiver.py プロジェクト: mariusmoe/KTN
    def run(self):
        # TODO: Make MessageReceiver receive and handle payloads
        parser = MessageParser()
        while True:
            self.received = self.connection.recv(1024)        # v2
            # print self.received

            print parser.parse(self.received)
コード例 #5
0
ファイル: Client.py プロジェクト: haakoneh/TTM4100_Project
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)
コード例 #6
0
ファイル: Client.py プロジェクト: ingridstoen/KTN-prosjekt
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)

        # Set up messageparser
        self.message_parser = MessageParser()

        try:
            self.run()
        except KeyboardInterrupt:  # Disconnect on keyboard interupt
            self.disconnect()

    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()

    def disconnect(self):
        print "Closing connection..."
        # Make sure the user is logged out
        payload = {"request": "logout", "content": ""}
        self.send_payload(json.dumps(payload))
        time.sleep(1)  # Wait for the logout payload to be sent
        self.connection.close()
        print "Connection terminated."

    def receive_message(self, payload):
        print self.message_parser.parse(payload)

    def send_payload(self, data):
        self.connection.send(data)
コード例 #7
0
ファイル: Client.py プロジェクト: kaisabr/TTM4100-KTN
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)
コード例 #8
0
ファイル: Client.py プロジェクト: erikebj/KTN_prosjekt
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)
コード例 #9
0
class SwankRatsWebSocketClient(WebSocketClient):
    def opened(self):
        self.form = RobotConfig.Config.get("robot", "form")
        print("opened " + self.form)
        self.parser = MessageParser()
        data = '{"to":"robot", "cmd":"init", "params":{"form":"' + self.form + '"} }'
        self.send(data)

    def closed(self, code, reason=None):
        print "Closed down", code, reason
        self.parser.robot.set(0, 0)
        os.system("shutdown /r")

    def received_message(self, m):
        print m
        self.parser.parse(m.data)
コード例 #10
0
class MessageReceiver(threading.Thread):
    """
    This is the message receiver class. The class inherits Thread, something that
    is necessary to make the MessageReceiver start a new thread, and it allows
    the chat client to both send and receive messages at the same time
    """
    def __init__(self, client, connection):
        """
        This method is executed when creating a new MessageReceiver object
        """
        threading.Thread.__init__(self, name=client)
        # Flag to run thread as a deamon
        self.daemon = True
        self.connection = connection
        self.parser = MessageParser()
        #self.run()

    def run(self):
            while True:
                payload = self.connection.recv(4096)
                jresponses = payload.decode("utf-8").split("\0")
                for jresponse in jresponses:
                    if jresponse is not None and len(jresponse) > 0:
                        try:
                            response = dejsonify(jresponse)
                            print(self.parser.parse(response))#, end='')
                        except:
                            print("Couldn't dejsonify: ( ", jresponse, " )")
                        """
コード例 #11
0
ファイル: MessageReceiver.py プロジェクト: eirikjohannes/ktn
class MessageReceiver(Thread):
    def __init__(self, client, connection):
        super(MessageReceiver, self).__init__()
        #self.thread = Thread(target=self.run)
        self.daemon = True
        self.client = client
        self.connection = connection
        self.msgParser = MessageParser()

    def run(self):
        while True:
            try:
                incomingMessage = self.connection.recv(4096)
            except:
                print bcolors.WARNING + "Failed when trying to read socket, restart program" + bcolors.ENDC
                break

            if incomingMessage != "":
                parsedMessage = self.msgParser.parse(incomingMessage)
                if parsedMessage == "logout":
                    self.stop()
                else:
                    print(parsedMessage)
                #self.stop()
        pass

    def stop(self):
        self.client.disconnect()
コード例 #12
0
ファイル: MessageReceiver.py プロジェクト: Dyscalculia/Jalc
class MessageReceiver(Thread):
    """
    This is the message receiver class. The class inherits Thread, something that
    is necessary to make the MessageReceiver start a new thread, and it allows
    the chat client to both send and receive messages at the same time
    """

    def __init__(self, client, connection):
        """
        This method is executed when creating a new MessageReceiver object
        """

        Thread.__init__(self)

        # Flag to run thread as a deamon
        self.daemon = True

        self.client = client
        self.connection = connection

        self.msgparser = MessageParser()

        # TODO: Finish initialization of MessageReceiver

    def run(self):
        # TODO: Make MessageReceiver receive and handle payloads
        while True:
            data = self.connection.recv(2048)
            #print "Klient motttok: " + data
            for json_msg in data.split("}"):
                if len(json_msg) > 5:
                    self.client.receive_message(self.msgparser.parse(json_msg + "}", self))
コード例 #13
0
class SubredditWatcher:

    MAX_ALREADY_DONE_LENGTH = 2000

    def __init__(self, name, praw_reddit, triggers, username):
        self.name = name
        self.praw_reddit = praw_reddit
        self.triggers = triggers
        self.username = username
        self.already_done = []
        self.msg_parser = MessageParser(triggers)

    def watch(self):
        subreddit = self.praw_reddit.get_subreddit(self.name)
        util.bot_stdout_print("Getting comments for subreddit: %s" % (self.name))
        for submission in subreddit.get_comments():
            if submission.id not in self.already_done:
                try:
                    msg = submission.body
                    successes,failures = self.msg_parser.parse(msg)
                    self.already_done.append(submission.id)
                    reply = self.get_reply(submission, successes, failures)
                    if not reply is None:
                        util.bot_stdout_print("Reply to %s: %s\n" % (submission.id, reply))
                        util.handle_ratelimit(submission.reply, reply)
                except:
                    util.bot_stdout_print("Unknown exception: %s" % sys.exc_info()[0])
                    print traceback.format_exc()
                    self.already_done.append(submission.id)
        self.cleanup_already_done()

    def get_reply(self, submission, successes, failures):

        if len(successes) > 0:
            success_msgs = []
            for result in successes:
                success_msgs.append("Random integer between %d and %d is %d." % (result["x"], result["y"], result["randnum"]))
            reply = "  \n".join(success_msgs)
            return reply

        elif len(failures) > 0:
            failure_messages = []
            for failure_msg in failures:
                failure_messages.append("* %s" % failure_msg)
            reply = "The following errors occurred:  \n  \n"
            reply += "  \n".join(failure_messages)
            reply += "  \n  \nYou may be doing something incorrectly."
            reply += " Please enter the following command to use this bot: "
            reply += "\"/u/%s x y\" (where x and y are integers)." % self.username
            return reply

    def cleanup_already_done(self):
        # Thought about just removing everything that is not in the current reddit comment list, 
        # but I'm not sure how reddit handles comment deletion. I'd hate for the bot to respond twice.
        # Instead, I'm just going to keep the list at a maximum length. This will at least keep the 
        # bot from consuming too much memory.
        if len(self.already_done) > self.MAX_ALREADY_DONE_LENGTH:
            negative_length = -1 * self.MAX_ALREADY_DONE_LENGTH
            self.already_done = self.already_done[negative_length:]
コード例 #14
0
class MentionsWatcher:

    MAX_ALREADY_DONE_LENGTH = 2000
    DELAY = 30

    def __init__(self, praw_reddit, username):
        self.praw_reddit = praw_reddit
        self.username = username
        self.already_done = []
        self.last_run = None
        self.msg_parser = MessageParser(username=username)

    def watch(self):
        now = int(time.time())
        if self.last_run is None or now - self.last_run > self.DELAY:
            util.bot_stdout_print("Getting mentions for user: %s" % (self.username))
            mentions = self.praw_reddit.get_mentions()
            self.last_run = int(time.time())
            try:
                for mention in mentions:
                    if mention.new == True and mention.id not in self.already_done:
                        msg = mention.body
                        successes,failures = self.msg_parser.parse(msg)
                        reply = self.get_reply(successes, failures)
                        self.already_done.append(mention.id)
                        mention.mark_as_read()
                        if not reply is None:
                            util.bot_stdout_print("Reply to %s: %s\n" % (mention.id, reply))
                            util.handle_ratelimit(mention.reply, reply)
            except:
                util.bot_stdout_print("Unknown exception: %s" % sys.exc_info()[0])
                print traceback.format_exc()
                self.already_done.append(mention.id)
            self.cleanup_already_done()

    def get_reply(self, successes, failures):
        if len(successes) > 0:
            success_msgs = []
            for result in successes:
                success_msgs.append("Random integer between %d and %d is %d." % (result["x"], result["y"], result["randnum"]))
            reply = "  \n".join(success_msgs)
            return reply
        elif len(failures) > 0:
            failure_messages = []
            for failure_msg in failures:
                failure_messages.append("* %s" % failure_msg)
            reply = "The following errors occurred:  \n  \n"
            reply += "  \n".join(failure_messages)
            reply += "  \n  \nYou may be doing something incorrectly."
            reply += " Please enter the following command to use this bot: "
            reply += "\"/u/%s x y\" (where x and y are integers)." % self.username
            return reply

    def cleanup_already_done(self):
        if len(self.already_done) > self.MAX_ALREADY_DONE_LENGTH:
            negative_length = -1 * self.MAX_ALREADY_DONE_LENGTH
            self.already_done = self.already_done[negative_length:]
コード例 #15
0
ファイル: Client.py プロジェクト: shivjr/TTM4100
 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)
コード例 #16
0
ファイル: Client.py プロジェクト: eskarpnes/KTN
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.username = None
        self.parser = MessageParser(self)
        self.connection.connect((self.host, self.server_port))
        self.receiver = MessageReceiver(self, self.connection)
        self.run()

    def run(self):
        while True:
            request = input()
            if request == "quit":
                self.disconnect()
            self.send_payload(request.split(" ", 1))

    def disconnect(self):
        self.connection.close()
        quit()

    def logout(self):
        self.username = None
        print("Logout successful")

    def receive_message(self, message):
        self.parser.parse(message)

    def send_payload(self, data):
        payload = json.dumps({
                "request": data[0],
                "content": data[1] if data[0] in ["msg", "login"] else None
            })
        self.connection.send(payload.encode())
コード例 #17
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
        """
        # Set up the socket connection to the server
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.msgParser = None
        self.host = host
        self.server_port = server_port
        self.run()

    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 disconnect(self):
        print("Disconnecting client...")
        self.send_payload('logout')

    def receive_message(self, message):
        print(self.msgParser.parse(message))

    def send_payload(self, data):
        request = None
        if data.startswith("login"):
            request = {'request' : 'login', 'content' : data[6:] }
        elif data.startswith("logout"):
            request = { 'request' : 'logout', 'content' : None}
        elif data.startswith("msg"):
            request = {'request' : 'message', 'content' : data[3:]}
        elif data.startswith("names"):
            request = {'request' : 'names', 'content' : None}
        elif data.startswith("help"):
            request = {'request' : 'help', 'content' : None }
        else:
            print("did not recognize command")
        if request:
            self.connection.sendall(json.dumps(request))
コード例 #18
0
 def run(self):
     # TODO: Make MessageReceiver receive and handle payloads
     while True:
         message_raw = self.connection.recv(4096) # bit to hardcoded?
         if not message_raw:
             self.client.disconnect()
         print("MessageReceiver received command") # temp
         message_parser = MessageParser()
         response = message_parser.parse(message_raw)
         self.client.print_line(response)
コード例 #19
0
class MessageReceiver(Thread):
    """
    This is the message receiver class. The class inherits Thread, something that
    is necessary to make the MessageReceiver start a new thread, and it allows
    the chat client to both send and receive messages at the same time
    """
    def __init__(self, client, connection):
        """
        This method is executed when creating a new MessageReceiver object
        """
        self.connection = connection
        super(MessageReceiver, self).__init__()

    def run(self):

        self.MessageParser = MessageParser()
        while True:
            payload = self.connection.recv(45096)
            self.MessageParser.parse(payload)
コード例 #20
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
        """

        # 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.receiver = MessageReceiver(self, self.connection)
        self.MessagePars = MessageParser()

        while True:
            input_ = raw_input().split(' ')
            if len(input_) != 0:
                if (input_[0] == "login"):
                    self.send_payload({
                        'request': 'login',
                        'content': input_[1]
                    })
                elif (input_[0] == "logout"):
                    self.send_payload({
                        'request': 'logout',
                    })
                elif (input_[0] == "msg"):
                    self.send_payload({'request': 'msg', 'content': input_[1]})
                elif (input_[0] == "names"):
                    self.send_payload({'request': 'names'})
                elif (input_[0] == "help"):
                    self.send_payload({'request': 'help'})
                else:
                    print "Error, type 'help'"

    def disconnect(self):
        self.connection.close()

    def receive_message(self, message):
        message = self.MessagePars.parse(message)
        print message

    def send_payload(self, data):
        payload = json.dumps(data).encode("utf-8")
        self.connection.send(payload)
コード例 #21
0
ファイル: Client.py プロジェクト: macytter/ktn_prosjekt
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
コード例 #22
0
ファイル: Client.py プロジェクト: macytter/ktn_prosjekt
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
コード例 #23
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
        """

        # 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.messageReciever = MessageReceiver(self, self.connection)
        self.messageParser = MessageParser()
        self.chatClient()

    def run(self):
        # Initiate the connection to the server
        self.connection.connect((self.host, self.server_port))

    def disconnect(self):
        self.connection.close()

    def recieve_message(self, message):
        messageAsString = self.messageParser.parse(message)
        print(messageAsString)

    def send_payload(self, data):
        self.connection.send(
            data)  #This assumes that "data" already is in JSON format

    def messageToPayload(self, message):
        # Converting user input to JSON format. Done in many steps to make the logic transparent
        splitMessage = message.split(None, 1)  #Separating request and content
        request = splitMessage[0] if len(splitMessage) > 0 else None
        content = splitMessage[1] if len(splitMessage) > 1 else None
        payloadAsDictionary = {'request': request, 'content': content}
        payload = json.dumps(payloadAsDictionary)
        return payload

    def chatClient(self):
        while True:
            userInput = raw_input()
            payload = self.messageToPayload(userInput)
            self.send_payload(payload)
コード例 #24
0
ファイル: Client.py プロジェクト: svennhv/simpleTCPmessaging
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()
        self.messageReciever = MessageReceiver(self,self.connection)
        self.messageParser = MessageParser()
        self.chatClient()

    def run(self):
        # Initiate the connection to the server
        self.connection.connect((self.host, self.server_port))
        
    def disconnect(self):
        self.connection.close()

    def recieve_message(self, message):
        messageAsString = self.messageParser.parse(message)
        print(messageAsString)

    def send_payload(self, data):
        self.connection.send(data) #This assumes that "data" already is in JSON format

    def messageToPayload(self, message):
        # Converting user input to JSON format. Done in many steps to make the logic transparent
        splitMessage = message.split(None, 1) #Separating request and content
        request = splitMessage[0] if len(splitMessage) > 0 else None
        content = splitMessage[1] if len(splitMessage) > 1 else None
        payloadAsDictionary = {'request' : request,'content' : content}
        payload = json.dumps(payloadAsDictionary)
        return payload

    def chatClient(self):
        while True:
            userInput = raw_input()
            payload = self.messageToPayload(userInput)
            self.send_payload(payload)
コード例 #25
0
    def run(self):
        parser = MessageParser()
        # TODO: Make MessageReceiver receive and handle payloads
        print("Start messageReceiver")
        while True:
            rawRecvMessage = self.connection.recv(4096)
            if rawRecvMessage:
                recvMessage = rawRecvMessage.decode()
                payload = parser.parse(recvMessage)

                if payload['response'] == 'error':
                    self.errorHandler(payload)
                elif payload['response'] == 'info':
                    self.infoHandler(payload)
                elif payload['response'] == 'history':
                    self.historyHandler(payload)
                elif payload['response'] == 'message':
                    self.messageHandler(payload)
コード例 #26
0
ファイル: Client.py プロジェクト: magnublo/KTN-prosjekt
class Client():

    def __init__(self, host, server_port):
        """
        This method is run when creating a new Client object
        """

        self.host = 'localhost'
        self.server_Port = 1337

        # Set up the socket connection to the server
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.receiver = None
        self.myParser = MessageParser()

        # TODO: Finish init process with necessary code
        self.run()

    def run(self):
        self.connection.connect((self.host, self.server_Port))
        self.receiver = MessageReceiver(self, self.connection)
        print "Give user input to the chat client."
        self.take_input()


    def receive_message(self, message):
        msg = (self.myParser.parse(message))
        if msg is not None:
            print msg

    def send_payload(self, data):
        self.connection.send(data)

    def take_input(self):
        userinput = raw_input()
        words = userinput.split(' ', 1)
        if len(words) == 2:
            message_as_dict = {'request': words[0], 'content': words[1]}
        else:
            message_as_dict = {'request': words[0], 'content': None}
        message_as_json = json.dumps(message_as_dict)
        self.send_payload(message_as_json)
        self.take_input()
コード例 #27
0
ファイル: Client.py プロジェクト: trimato/KTN
 def receive_message(self, message):
     # TODO: Handle incoming message
     #print("<-- " + message) # TODO: REMOVE DEBUG
     parser = MessageParser()
     parser.parse(message)
     pass
コード例 #28
0
ファイル: Client.py プロジェクト: matiasvc/KTN_project
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'))
コード例 #29
0
ファイル: Client.py プロジェクト: vnvestad/TTM4100
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)

        # Init
        self.host = host
        self.server_port = server_port
        self.state = State.LOGIN;

        self.messageEncoder = MessageEncoder()
        self.messageParser = MessageParser()

        self.username = ""

        # Run client
        self.run()

    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")



    def disconnect(self):
        self.connection.close()

    def receive_payload(self, payload):
        message = self.messageParser.parse(payload)
        if 'error' in message.keys():
            print("Error:", message['error'])
            self.state = State.LOGIN
        elif 'info' in message.keys():
            print("Info:", message['info'])
        elif 'message' in message.keys():
            if self.state == State.CHATROOM:
            	if message['sender'] != self.username:
                	print(message['sender']+":", message['message'])
        elif 'history' in message.keys():
            print("")
            print("Welcome", self.username, "to CHATROOM!")
            for msg in message['history']:
            	if msg['sender'] == self.username:
            		print(msg['message'])
            	else:
                	print(msg['sender']+":", msg['message'])
            self.state = State.CHATROOM

    def send_payload(self, payload):
    	if not self.connection._closed:
        	self.connection.send(payload.encode())
コード例 #30
0
ファイル: Client.py プロジェクト: Hovind/ktn-chat
 def receive_message(self, message):
     # TODO: Handle incoming message
     parser = MessageParser()
     print(parser.parse(message))
コード例 #31
0
ファイル: Client.py プロジェクト: pbsds/TTM4100-Chat
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
コード例 #32
0
 def receive_message(self, message):
     parser = MessageParser()
     messageType = parser.parse(message)
     print messageType
コード例 #33
0
ファイル: Client.py プロジェクト: simenbkr/TTM4100-KTN
 def receive_message(self, message, connection):
     parser = MessageParser()
     print parser.parse(message)
コード例 #34
0
ファイル: Client.py プロジェクト: Mattivc/KTN_project
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'))
コード例 #35
0
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'}
コード例 #36
0
ファイル: Client.py プロジェクト: sindrehan/TTM4100-Project
 def receive_message(self, message):
     parser = MessageParser()
     response = parser.parse(message)
     print response
コード例 #37
0
 def receive_message(self, message):
     message_parser = MessageParser()
     print(message_parser.parse(message))
コード例 #38
0
ファイル: Client.py プロジェクト: teatimes/TTM4100
class Client:
    """
	This is the chat client class
	"""

    in_chat = True

    def send_payload(self, data):
        # TODO: Handle sending of a payload
        # START

        json_object = None

        # Om bruker vil logge inn
        if data.startswith("login"):
            json_object = json.dumps(
                {
                    "request": "login",
                    # login + space = 6
                    "content": data[6:],
                }
            )
            # Om bruker vil logge ut
        elif data.startswith("logout"):
            json_object = json.dumps({"request": "logout", "content": None})
            in_chat = False
            self.disconnect()

            # Om bruker ber om navnene til dem i chatten
        elif data.startswith("name"):
            json_object = json.dumps({"request": "name", "content": None})

            # Om brukeren trenger hjelp
        elif data.startswith("help"):
            json_object = json.dumps({"request": "help", "content": None})

            # Om bruker vil sende melding
        else:
            json_object = json.dumps({"request": "msg", "content": data})

            # Sender til server
        self.connection.send(json_object)

        # END

        pass

        # Får host og severport fra main funksjonen nederst (host = "localhost" og server_port = 9993)

    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)

                # END

                # self.run()

                # def run(self):
                # Initiate the connection to the server
                # self.connection.connect((self.host, self.server_port))

    def disconnect(self):
        # TODO: Handle disconnection
        # START

        # TODO Får feilmelding på shutdown
        # self.connection.shutdown()
        # self.connection.close()
        print("You are now logged out.")

        # END
        pass

    def receive_message(self, message):
        # TODO: Handle incoming message

        # START
        # Får meldinger fra MessageReceiver (respons fra server)
        # Som må videresendes til MessageParser som returnerer en string
        # som så kan printes

        # Sender json-objektet til MessageParser
        parsedMessage = self.parser.parse(message)

        # Printer stringen MessageParser returnerer
        print(parsedMessage)

        # END
        pass
コード例 #39
0
ファイル: Client.py プロジェクト: S1GGEN/urban-robot
 def receive_message(self, message):
     parser = MessageParser()
     parsed_message = MessageParser.parse(parser, message)
     print(str(parsed_message))
コード例 #40
0
ファイル: Client.py プロジェクト: agnetedjupvik/chatter
 def receive_message(self, message):
     print "Received message:" + message
     parser = MessageParser()
     parsedMessage = parser.parse(message)
     print parsedMessage
     pass
コード例 #41
0
ファイル: Client.py プロジェクト: Shamzaa/KTN
 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");
コード例 #42
0
ファイル: Client.py プロジェクト: emilte/chat_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.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connection.settimeout(0.1)
        # TODO: Finish init process with necessary code
        self.host = host
        self.server_port = server_port
        self.MessageParser = MessageParser()
        self.disconnected = False
        self.run()

    def run(self):
        # Initiate the connection to the server
        self.connection.connect((self.host, self.server_port))
        self.MessageReceiver = MessageReceiver(self, self.connection)
        self.MessageReceiver.start()

        while not self.disconnected:
            # Lager tom pakke som skal sendes til server:
            self.data = {'request': None, 'content': None}

            # Henter request fra bruker:
            self.request = input(" > ")
            if (self.request == ""):
                continue

            elif (self.request == "login"):
                self.data['request'] = self.request
                self.data['content'] = input("username: "******"names", "logout", "help"]):
                self.data['request'] = self.request

            else:  #Bare vanlig msg:
                self.data['request'] = "msg"
                self.data['content'] = self.request

            # Gjør om pakken til JSON:
            self.data_json = json.dumps(self.data)
            # Sender pakken til serveren:
            self.connection.send(self.data_json.encode())
            # Sleep så man rekker å disconnecte
            time.sleep(0.5)

    def disconnect(self):
        self.disconnected = True
        MessageReceiver.stop()
        self.connection.close()

    def receive_message(self, message):
        self.payload = message

        self.data_string = self.MessageParser.parse(self.payload)
        print(self.data_string)

        message = json.loads(message)
        if ("Logout successful" == message['content']
                and "info" == message['response']):
            self.disconnect()
コード例 #43
0
 def receive_message(self, message):
     print 'in receive'
     MessageParser.parse(message)
     print 'after parse'
コード例 #44
0
ファイル: Client.py プロジェクト: Daffee/Komnett-prosjekt
 def receive_message(self, message):
     print 'in receive'
     MessageParser.parse(message)
     print 'after parse'
コード例 #45
0
 def receive_message(self, message):
     parser = MessageParser()
     parsed_message = parser.parse(message)
     print(parsed_message, '\n> ', end='')
コード例 #46
0
ファイル: Client.py プロジェクト: einarwar/KTNirc
 def receive_message(self, message):
     # TODO: Handle incoming message
     parser = MessageParser()
     parsed = parser.parse(json.loads(message))
     print parsed
コード例 #47
0
ファイル: Client.py プロジェクト: DamnStr4ight/TTM4100-KTN
 def receive_message(self, message):
     # TODO: Handle incoming message
     parser = MessageParser()
     parsed_message = parser.parse(message)
     print(parsed_message, '\n> ', end='')
コード例 #48
0
 def receive_message(self, message):
     # TODO: Handle incoming message
     messageParser = MessageParser()
     response = messageParser.parse(message)
     print(response)
コード例 #49
0
ファイル: Client.py プロジェクト: sindrehan/TTM4100-Project
 def receive_message(self, message):
     parser = MessageParser()
     response = parser.parse(message)
     print response
コード例 #50
0
ファイル: Client.py プロジェクト: rubenbu/gallis
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
コード例 #51
0
ファイル: Client.py プロジェクト: powermundsen/ktn
 def receive_message(self, message):
     message_parser = MessageParser()
     message_parser.parse(message)
     pass
コード例 #52
0
 def receive_message(self, message, connection):
     parser = MessageParser()
     print parser.parse(message)
コード例 #53
0
ファイル: Client.py プロジェクト: BentHeier/ktn
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()

        # 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 run(self):
        # Initiate the connection to the server
        self.connection.connect((self.host, self.server_port))
        
    def disconnect(self):
        # LOGOUT
        self.connection.close()

    def receive_message(self, message):
        parsed_message = self.parser.parse(message)
        self.display_message(parsed_message)

    def send_payload(self, data):
        input_splitted = data.split(' ', 1)
        firstWord = input_splitted[0]

        # Create json object based on the structure of the data string
        if firstWord == 'login':
            # Find username from data_string
            if len(input_splitted) is not 2 or input_splitted[1] is "":
                return
            username = input_splitted[1]
            payload = json.dumps({"request": "login", "content": username})

        elif firstWord == 'logout':
            payload = json.dumps({"request": "logout", "content": None})
        elif firstWord == 'names':
            payload = json.dumps({"request": "names", "content": None})
        elif firstWord == 'help':
            payload = json.dumps({"request": "help", "content": None})
        else:
            # Find message from the data string
            message = data
            payload = json.dumps({"request": "msg", "content": message})
        self.connection.send(payload)
        
    def display_message(self, message):
        print message
コード例 #54
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
        """

        # 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))
コード例 #55
0
ファイル: Client.py プロジェクト: finnss/KTN-Project
 def receive_message(self, message):
     parser = MessageParser()
     parsed_message = parser.parse(message)
     print(parsed_message,'\n> ',end='')
コード例 #56
0
ファイル: Client.py プロジェクト: mariusmoe/KTN
 def receive_message(self, message):
     # TODO: Handle incoming message
     # print "Received: {}".format(received)
     self.out_text = MessageParser.parse(message)
     print " > " + self.out_text
コード例 #57
0
 def receive_message(self, message):
     parser = MessageParser()
     messageType = parser.parse(message)
     print messageType