Example #1
0
 def send_message(self, from_kingdom, to_kingdom, message):
     from_kingdom = self.kingdoms[from_kingdom]
     to_kingdom = self.kingdoms[to_kingdom]
     self.set_competing_kingdoms(from_kingdom)
     message = Message(from_kingdom, to_kingdom, message)
     if message.is_code_present():
         from_kingdom.set_allies(to_kingdom)
Example #2
0
    def listen(self, client_num:int) -> None:
        """
        Listen thread that listen to the given client.

        Parameters
        ----------
        client_num : int
            [description]

        Raises
        ------
        Exception
            Unexpected message header
        """
        
        self.display(f"[i] The socket server is now listening to #{client_num}.")    #TODO
        user_socket = self.users[client_num].socket
        
        while True:     
            self.display("'m in...")
            data = user_socket.recv(self.buff_size)
            self.display("data received")
            msg = Message()
            self.display("msg obj created")
            self.display(f"the data : {data.decode()}")
            msg.parse(data.decode())
            print(f"the message is : {msg}")
            
            if msg.header == "USERNAME":
                self.display("we got an username")
                self.users[client_num].username = msg.content
            elif msg.header == "ENCODING":
                pass
            elif msg.header == "ENCODING_ERRORS":
                pass
            elif msg.header == "MSG":
                self.redirect(msg)
            elif msg.header == "DM":
                pass
            elif msg.header == "USERS":
                pass
            elif msg.header == "KICK":
                pass
            elif msg.header == "BAN":
                pass
            elif msg.header == "QUIT":
                pass
            elif msg.header == "KILL":
                self.kill()
            else:
                self.display(f"[X] Unexpected header : {msg.header}.")
Example #3
0
    def output_method(self) -> None:
        """
        [summary]
        """

        while True:
            data = self.socket.recv(self.buff_size)
            msg = Message()
            msg.parse(data.decode())
            if msg.header == "MSG":
                self.outputs.append(msg.content)
                self.output_field.clear()
                self.output_field.addstr(0, 0, "\n".join(self.outputs))
                self.output_field.refresh()
Example #4
0
    def simulate_adding_packets_into_buffer(self, dest):
        #  This function is used in the test mode
        ''' This method generates the actual 'real' messages for which we compute the entropy.
            The rate at which we generate this traffic is defined by rate_generating variable in
            the config file.
​
            Keyword arguments:
            dest - the destination of the message.
        '''
        i = 0

        # Note: if you want to send messages or larger size than a single packet this function must be updated
        while i < self.conf["misc"]["num_target_packets"]:

            yield self.env.timeout(float(self.rate_generating))

            msg = Message.random(conf=self.conf,
                                 net=self.net,
                                 sender=self,
                                 dest=dest)  # New Message
            current_time = self.env.now
            msg.time_queued = current_time  # The time when the message was created and placed into the queue
            for pkt in msg.pkts:
                pkt.time_queued = current_time
                pkt.probability_mass[i] = 1.0
            self.add_to_buffer(msg.pkts)
            self.env.message_ctr += 1
            i += 1
        self.env.finished = True
 def sendMessage(self, text, sender):
     """creates a new message and appends in to our current conversation messages"""
     assert isinstance(sender, classes.User.User)
     new_message = Message(m_author=sender,
                           m_aud=self.participants,
                           new_message=True,
                           m_body=text)
     self.messages.append(new_message)
     raise NotImplementedError
Example #6
0
    def input_method(self) -> None:
        """
        [summary]
        """

        while True:
            new_char = self.input_field.getch()

            if new_char in self.KEYS_PRINTABLE:
                if len(self.user_input
                       ) < 233:  #TODO: accoding to the field size
                    try:
                        new_input = chr(new_char)
                        self.user_input += new_input
                    except ValueError:
                        raise Exception(f"Invalid new input : {new_char}")

            elif new_char in self.KEYS_ENTER:
                # parsing commands
                if self.user_input.startswith("/"):
                    if self.user_input[1:] in ["leave", "exit"]:
                        pass
                # sending message
                else:
                    self.display("msg sent")
                    msg = Message(header="MSG", content=self.user_input)
                    self.socket.sendall(
                        msg.encoded(self.encoding, self.encoding_errors))

                self.user_input = ""

            elif new_char in self.KEYS_BACKSPACE:
                self.user_input = self.user_input[:-1]

            elif new_char == self.KEY_ESCAPE:
                exit()

            else:
                self.log("ERROR", "unknwown imput")

            self.input_field.clear()
            self.input_field.addstr(0, 0, self.user_input)
            self.input_field.refresh()
Example #7
0
    def connect(self, host: str = "127.0.0.1", port: int = 9999) -> None:
        """
        Connect to a NetChat server.

        Parameters
        ----------
        host : str, optional
            server-target's IP address, by default "127.0.0.1"
        port : int, optional
            server-target's port, by default 9999
        """

        # asserts
        assert isinstance(
            host,
            str), f"Invalid 'host' data type : {type(host)}. Expected a str."
        assert isinstance(
            port,
            int), f"Invalid 'port' data type : {type(port)}. Expected an int."

        # attributes from arguments
        self.host = host
        self.port = port

        with socket.socket() as server:
            self.socket = server
            self.socket.connect((host, port))
            username_msg = Message(header="USERNAME", content=self.username)
            server.sendall(username_msg.encoded())

            self.display(f"[i] connected to {host}:{port}")

            input_thread = Thread(target=self.input_method)
            output_thread = Thread(target=self.output_method)
            input_thread.start()
            output_thread.start()
            input_thread.join()
            output_thread.join()
Example #8
0
    def redirect(self, msg:Message) -> None:
        """
        Redirect the given message to the clients.

        Parameters
        ----------
        msg : Message
            [description]
        """
        for user in self.users:
            try:
                self.display(f"[i] trying to redirect to #{user.uuid}")
                user.socket.sendall(msg.encoded())
                self.display(f"[>] Message sent to #{user.uuid}") #TODO
            except ConnectionResetError:
                self.display("[X] Unreacheable target")
Example #9
0
 def addMessage(self, username, sender, text):
     msg = Message(sender, text)
     if self.messages.get(username) is None:
         self.messages[username] = []
     self.messages[username].append(msg)
Example #10
0
                        *client_address, userName))
            else:
                message = receive_raw_message_with_header(notified_socket)
                if message is False:
                    print('Closed connection from: {}'.format(user.name))
                    sockets_list.remove(notified_socket)
                    del clients[notified_socket]
                    continue
                user = clients[notified_socket]
                decodedMessage = message["data"].decode("utf-8")
                print(f'Received message from {user.name}: {decodedMessage}')
                messageToSend = {}
                if (message['data'].decode('utf-8')[0] == '/'):
                    messageToSend = getCommand(decodedMessage, user)
                else:
                    messageToSend = Message(decodedMessage, '')

                for client_socket in clients:
                    if client_socket != notified_socket:
                        if (len(messageToSend.to_others) > 0):
                            client_socket.send(
                                user.header.encode('utf-8') +
                                user.name.encode('utf-8') +
                                messageToSend.header_to_others +
                                messageToSend.to_others)
                    else:
                        if (len(messageToSend.reply) > 0):
                            client_socket.send(
                                user.header.encode('utf-8') +
                                user.name.encode('utf-8') +
                                messageToSend.header_reply +
 async def getInvite(self, guild: discord.guild.Guild):
     for channel in guild.text_channels:
         msgs = channel.history()
         for msg in msgs:
             _msg = Message(msg)