def new_msg_handle(self, message):
        """
        Обработка сообщений пользователей
        """
        # текст сообщения
        body = message[MESSAGE]
        # от кого
        from_ = message[FROM]
        to = message[TO]

        # обработка сообщений.
        if self.is_client_online(to):
            for transport, account_name in self.connections.items():
                # Перебираем все подключения.
                # Если один и тот же клиент будет сидеть с разных клиентов,
                # он получит свое сообщение на все клиенты
                if account_name == to:
                    # Формирует сообщение для отправки с сервера
                    response = {
                        ACTION: MSG,
                        TIME: time.time(),
                        TO: account_name,
                        FROM: from_,
                        MESSAGE: body
                    }
                    # Отправляем
                    transport.write(dict_to_bytes(response))
        else:
            # Отправляем что клиента нету в сети
            response = {RESPONSE: BASIC_NOTICE, ALERT: 'Клиента нет в сети'}
            self.transport.write(dict_to_bytes(response))
 def send_error_message(self, text):
     """
     Отправляет клиенту сообщение об ошибке
     """
     response = {RESPONSE: WRONG_REQUEST, ALERT: text}
     # self.transport - это наш канал общения с текущим клиентом
     self.transport.write(dict_to_bytes(response))
Example #3
0
def udp_incoming():
    global latest_registration_lock
    global latest_registration
    global resend_register
    global items
    global items_lock
    # there are times when the UDP server will send all connected clients a msg such as NEW-ITEM msg's
    while True:
        message, addr = udp_socket.recvfrom(4096)
        message = message.decode('utf-8')
        msg_dict = ast.literal_eval(message)
        if msg_dict['type'] == UNREGISTERED and resend_register is True:
            with latest_registration_lock:
                reg = latest_registration
            resend_register = False
            send_bytes = dict_to_bytes(reg)
            with udp_msg_lock:
                udp_messages.append(send_bytes)
        elif msg_dict['type'] == UNREGISTERED and resend_register is False:
            resend_register = True

        if msg_dict['type'] == UPDATE_CLIENTS:
            update_txt(UPDATE_STATE, msg_dict['items'])
            with items_lock:
                items = msg_dict['items']
            continue
        elif msg_dict['type'] == SERVER_CRASHED:
            update_txt(SERVER_CRASHED, msg_dict['description'])
            continue
        # elif msg_dict['type'] == ITEMPORT:  #
        #     global current_port
        #     current_port = msg_dict['port']
        #     print(current_port)
        print("Received udp message: " + message)
        update_txt(RETURN_MSG, message)
Example #4
0
 def quit(self):
     server.send(
         dict_to_bytes({
             "action": "quit",
             "time": time.time(),
             "account_name": self.account_name
         }))
     server.close()
     exit(0)
Example #5
0
 def presence(self, status):
     server.send(
         dict_to_bytes({
             "action": "presence",
             "time": time.time(),
             "user": {
                 "account_name": self.account_name,
                 "status": status
             }
         }))
Example #6
0
 def authenticate(self):
     server.send(
         dict_to_bytes({
             "action": "authenticate",
             "time": time.time(),
             "user": {
                 "account_name": self.account_name,
                 "password": self.password
             }
         }))
Example #7
0
 def msg(self):
     to = input('кому:')
     message = input('сообщение:')
     server.send(
         dict_to_bytes({
             "action": "msg",
             "time": time.time(),
             "to": to,
             "from": self.account_name,
             "encoding": "ascii",
             "message": message
         }))
 def presence_handle(self, message):
     """
     Обработчик presence
     """
     # получаем имя пользователя
     account_name = message[USER][ACCOUNT_NAME]
     # формируем ответ
     response = {RESPONSE: OK}
     # отправляем self.transport - это текущий клиент
     self.transport.write(dict_to_bytes(response))
     # добавляем клиента в соединения
     # добавляем клиента в текущие соединения, его как ключ и его имя значением
     self.connections[self.transport] = account_name
Example #9
0
 def test_dict_to_bytes(self):
     with self.assertRaises(TypeError):
         dict_to_bytes('abc')
     self.assertEqual(dict_to_bytes({'test': 'test'}), b'{"test": "test"}')
 def test_dict_to_bytes(self):
     self.assertEqual(type(dict_to_bytes(message)), bytes)
from utils import bytes_to_dict, dict_to_bytes
import unittest

message = {'user': '******', 'action': 'presence'}

bmessage = dict_to_bytes(message)


class TestDictToBytes(unittest.TestCase):
    def test_dict_to_bytes(self):
        self.assertEqual(type(dict_to_bytes(message)), bytes)


class TestBytesToDict(unittest.TestCase):
    def test_bytes_to_dict(self):
        self.assertEqual(type(bytes_to_dict(bmessage)), dict)


if __name__ == '__main__':
    unittest.main()
Example #12
0
def get_user_command():  # should be set on start up, include when sending TCP msg's
    """This function gives the user their options of different actions they can take
        and either returns None if their choice doesn't exist or the msg to be send
         over UDP to the server"""

    # todo the server should keep track of the request numbers so if the client initiates the contact how does it know
    # todo which request numbers are already taken or not???

    """
        Get a command from the user, determine if TCP or UDP msg will be sent and form msg
        then put in respective queue for dispatch by either TCP or UDP thread in client.py
    """
    choice = input("Enter a command: \n" +
                   "'r' ==> Registration and offers\n" +
                   "'b' ==> Bidding etc.\n" +
                   "'c' ==> Cancel, will free up terminal to display any responses from server\n::")
    if choice is 'r':
        selection = input("Enter a command: \n" +
                          "'r' ==> Registrations \n" +
                          "'of' ==> Offers:: \n")
        if selection == 'r':
            register_unregister = input("Enter a command: \n" +
                                        "'r' ==> Register to be able to offer or bid\n" +
                                        "'d' ==> De-register if you are already registered\n::")
            if register_unregister == 'r':
                send_msg = get_registration(MY_TCP_PORT)
            elif register_unregister == 'd':
                send_msg = get_unregistration()
            else:
                print("That option isn't available")
                return None
        elif selection == 'of':
            send_msg = get_offer()

        try:
            send_bytes = dict_to_bytes(send_msg)
            with udp_msg_lock:
                udp_messages.append(send_bytes)
        except UnboundLocalError:
            pass

    elif choice is 'b':
        """Before bidding for a given item, a registered client has to establish a TCP connection to
            the TCP socket associated with the item of interest at the server side. After this
            connection, a client can bid on the item by sending a BID message."""
        print("These are the items available:")
        # message to show all items
        send_msg = show_all_messages()
        # need to differentiate these two messages
        
        try:
            send_bytes = dict_to_bytes(send_msg)
            with udp_msg_lock:
                udp_messages.append(send_bytes)
        except UnboundLocalError:
            pass
        sleep(0.5)  # temp fix for display to allow udp incoming thread to run before the rest of the code runs



        #send_msg = get_port()
        try:
            send_bytes = dict_to_bytes(send_msg)
            with udp_msg_lock:
                udp_messages.append(send_bytes)
        except UnboundLocalError:
            pass
        sleep(2)  # need to fix this

        if current_port != 0:
            #send_msg = get_bid(HOST, current_port)

            global start_receiving_tcp_messages
            start_receiving_tcp_messages = True

            try:
                send_bytes = dict_to_bytes(send_msg)
                with tcp_msg_lock:
                    tcp_messages.append(send_bytes)
            except UnboundLocalError:
                pass
        else:
            print("This item does not exit")
    elif choice is 'c':
        return
    else:
        print("That option isn't available")
        return None
Example #13
0
def gui_msg(udp_messages_, udp_msg_lock_, CLIENT_MSG_NUMBER_):
    # global CLIENT_MSG_NUMBER
    # global udp_msg_lock
    # global udp_messages
    global latest_registration
    global latest_registration_lock
    global port_lock
    global items
    global current_port
    # global resend_register
    # path = '/home/ryan/PycharmProjects/SERVER/state.txt'
    # item_list = open(path, 'r')
    # cport = 0
    global REGISTER
    """ Read the next last line of text from toClient.txt and if """
    # todo read the next line in toClient.txt and put the msg in the correct queue
    while True:
        with open('toClient.txt', 'r') as f:
            for line in f:  # line ===> (number, state_dict)
                try:
                    line = ast.literal_eval(line)
                    if int(line[0]) >= CLIENT_MSG_NUMBER_:
                        print("reading toClient.txt")
                        CLIENT_MSG_NUMBER_ += 1
                        msg_for_server = line[2]
                        if line[1] == REGISTER:
                            with latest_registration_lock:
                                latest_registration = line[2]
                        msg_for_server['request'] = req_number()
                        send_bytes = dict_to_bytes(line[2])
                        if line[1] == BID:  # BID is the only kind of msg to be sent over TCP? I think so
                            item = line[2]['item #']
                            amount = line[2]['amount']
                            name = line[2]['name']
                            global current_item
                            if item == current_item:  # meaning on new socket connection should be made
                                pass
                            else:
                                current_item = item
                                '''
                                send_msg = get_port(item)
                                send_bytes = dict_to_bytes(send_msg)
                                with udp_msg_lock:
                                    udp_messages.append(send_bytes)
                                '''
                                for it in items:
                                    if int(it['item #']) == int(item):
                                        current_port = it['port #']
                                sleep(1.0)
                                # with open('/home/ryan/PycharmProjects/SERVER/state.txt', 'r') as file:
                                #     state_ = file.read()
                                #     state_ = ast.literal_eval(state_)
                                #     items = state_['items']
                                #     for obj in items:
                                #         if int(obj['item #']) == int(item):
                                #             global current_port
                                #             current_port = obj['port #']

                                establishTcpConnection(SERVER_IP, current_port)
                            sleep(0.8)
                            if current_port != 0:
                                send_msg = get_bid(HOST, current_port, amount, name, item)

                                global start_receiving_tcp_messages
                                start_receiving_tcp_messages = True

                                send_bytes = dict_to_bytes(send_msg)
                                tcp_messages.append(send_bytes)

                            send_msg = show_all_messages()

                            send_bytes = dict_to_bytes(send_msg)
                            with udp_msg_lock:
                                udp_messages.append(send_bytes)

                        else:  # else if not a bid we send over UDP
                            with udp_msg_lock_:
                                udp_messages_.append(send_bytes)
                        # try:
                        #     send_bytes = dict_to_bytes(line[2])
                        #     with udp_msg_lock:
                        #         udp_messages.append(send_bytes)
                        # except UnboundLocalError:
                        #     pass
                        # msg_to_queue(udp_messages, udp_msg_lock, line[2])
                except SyntaxError:
                    print("Could not read line in toClient.txt")
                    pass