Example #1
0
 def threaded_client(self, clientsocket, addr):
     client_id = addr[1]
     client_handler = ClientHandler(self, clientsocket, addr) # self is the server instance
     client_handler.run() # inits all the components in client handler object
     #  adds the client handler object to the list of all the clients objects created by this server.
     #  key: client id, value: client handler
     self.client_handlers[client_id] = client_handler # assumes dict was initialized in class constructor
Example #2
0
    def client_handler_thread(self, clientsocket, address):
        """
        Sends the client id assigned to this clientsocket and
        Creates a new ClientHandler object
        See also ClientHandler Class
        :param clientsocket:
        :param address:
        :return: a client handler object.
        """
        ### ADDED ADDRESS HERE CAUSE WASNT HERE N CAUSED ERRORS
        self.send_client_id(clientsocket, address[1])
        # TODO: create a new client handler object and return it

        lock = threading.Lock()
        ch = ClientHandler(self, clientsocket, address)
        menu = Menu(clientsocket)
        sm = (menu.show_menu())
        sd = {'c_menu': sm}

        while True:
            self.send(clientsocket, sm)

            lock.acquire()

            # self.send(clientsocket, sm)
            ch.process_options()

            lock.release()

            # return x
        clientsocket.close()
Example #3
0
def main():
    server = Server()
    server.initialize_socket()
    while True:
        client_socket = server.connect_clients()
        c = ClientHandler(client_socket, server.connected_client_list)
        c.start()
Example #4
0
def client_configs(request, client_id):
    if client_id.isdigit():
        client_handler = ClientHandler()
        client_config = client_handler.get_configs(client_id)
        return HttpResponse(json.dumps(client_config))

    else:
        return HttpResponse("client id error")
Example #5
0
 def entry(self):
     listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     listener.bind(('127.0.0.1', config.LISTEN_PORT))
     listener.listen()
     while True:
         client, _ = listener.accept()
         if win32event.WaitForSingleObject(self.stop_event, 1) == win32event.WAIT_OBJECT_0:
             break
         t = ClientHandler(client)
         t.start()
Example #6
0
 def start(self):
     logging.info('Listening on port {}.'.format(listenPort))
     while True:
         try:
             (clientSock, (address, port)) = self.sock.accept()
             logging.info('Connecting to {}.'.format(address))
             clientHandler = ClientHandler(clientSock)
             clientHandler.start()
         except socket.error as err:
             logging.error('Encountered socket error: {}.'.format(err))
 def client_handler_thread(self, clientsocket, address):
     """
     Sends the client id assigned to this clientsocket and
     Creates a new ClientHandler object
     See also ClientHandler Class
     :param clientsocket:
     :param address:
     :return: a client handler object.
     """
     # are we not sending data?
     # self.send_client_id(clientsocket,address[1])
     #TODO: create a new client handler object and return it
     chObject = ClientHandler(self, clientsocket, address)
     chObject.process_client_data()
     return chObject
Example #8
0
def handler2(connfd):
    '''客户端处理函数'''

    # 引入全局变量
    global LoginUser
    global AllRoom
    global Log

    addr = connfd.getpeername()
    print("客户端连接", addr)
    # Log.append(get_time() + '客户端连接' + str(addr))
    # 写日志
    log.logging.info('客户端连接{}'.format(addr))
    handler = ClientHandler(connfd, LoginUser, AllRoom, Log)
    handler.data_recv()
Example #9
0
    def chat_room(self):
        try:
            room_info = input("\nEnter new room id: ")
            chat_id = input("Enter new chat room id: ")

            new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            new_socket.bind((self.ip, self.port))
            new_socket.listen(10)
            client_sock, addr = new_socket.accept()
            c_handler = ClientHandler(self, client_sock, addr)

            c_handler._create_chat(new_socket, room_info, chat_id,
                                   self.client_name)
        except:
            print("No room")
Example #10
0
    def client_handler_thread(self, clientsocket, address):
        """
        Sends the client id assigned to this clientsocket and
        Creates a new ClientHandler object
        See also ClientHandler Class
        :param clientsocket:
        :param address:
        :return: void
        """

        #self.send_client_id(clientsocket,address[1])
        #TODO: create a new client handler object and return it
        clienthandler = ClientHandler(self, clientsocket, address)
        clienthandler.clientSetUp()
        """     
Example #11
0
    def __init__(self):
        parser = argparse.ArgumentParser(
            description='Multi text editor server launcher')

        parser.add_argument('-i',
                            '--ip',
                            type=str,
                            help='ip address for server to listen',
                            required=False,
                            default=self.listen_ip)
        parser.add_argument('-p',
                            '--port',
                            type=int,
                            help='port for server to listen',
                            required=False,
                            default=self.listen_port)
        parser.add_argument('-d',
                            '--dir',
                            type=str,
                            help='users files directory (relative path)',
                            required=False,
                            default=self.users_dir)

        args = parser.parse_args()
        self.listen_ip = args.ip
        self.listen_port = args.port
        self.host = (self.listen_ip, self.listen_port)
        self.users_dir = args.dir
        file_service = FileService(Path.cwd() / self.users_dir)
        user_service = UserService(Path.cwd() / self.users_dir)
        self.client_handler = ClientHandler(user_service, file_service)
Example #12
0
    def _loop_clients(self):
        # Create a TCP/IP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Bind the socket to the port
        server_address = (self.address, self.port)
        logging.debug("Server started on " + self.address + ":" +
                      str(self.port))
        self.sock.bind(server_address)

        # Listen for incoming connections
        self.sock.listen(1)

        self.clients = []
        while self.server_is_running:
            logging.debug("Waiting for a connection...")
            connection = None
            try:
                connection, client_address = self.sock.accept()
                if self.server_is_running:
                    logging.debug("connection accepted from " +
                                  str(client_address))
                    client = ClientHandler(connection, client_address)
                    thread = Thread(target=client.start_handler)
                    thread.start()
                    self.lock.acquire()
                    self.clients.append(client)
                    self.lock.release()
            except Exception as e:
                logging.debug("Server forced to stop")
                if connection is not None:
                    connection.close()
async def test_client_handler_new_patch(user_svc, file_svc):
    mock_client = MagicMock()
    doc = Doc()
    patch = doc.insert(0, "A")
    file_id = FileService.get_file_id("r", "test")
    msg = {
        "username": "******",
        "password": "******",
        "filename": "test",
        "type": "patch",
        "content": patch,
        "file_id": file_id
    }
    raw_msg = json.dumps(msg).encode("utf-8")
    mock_client.__aiter__.return_value = [raw_msg]
    mock_client.return_value.send.return_value = Future()
    mock_client.return_value.send.return_value.set_result("123")
    user_svc.auth_user.return_value = False
    MagicMock.__await__ = lambda x: async_magic().__await__()

    user_svc_instance = user_svc.return_value()
    user_svc_instance.auth_user.return_value = True
    user_svc_instance.has_access.return_value = True
    file_svc_instance = file_svc.return_value()
    file_svc_instance.register_patch.return_value = None
    client_handler = ClientHandler(user_svc_instance, file_svc_instance)
    client_handler.active_authors.append({
        "connection": mock_client,
        "current_file": file_id
    })

    await client_handler.handle_client(mock_client, None)
    response = mock_client.send.call_args.args[0]

    assert json.loads(response)["content"] == patch
Example #14
0
    def connection(self):
        self.block_controls(True)

        # Инициализация потока, работающего с сокетами
        self.handler = ClientHandler(
            host=self.host.text(
            ),  # Передача параметров хоста (с текстового поля)
            port=self.port.value()  # Передача параметров порта
        )
        # Задание событию нажатия кнопки "Отправить" действия по отправке файла
        self.handler.for_receive.connect(
            lambda sock: self.send_button.clicked.connect(
                partial(self.send, sock=sock)))
        # Задание событию получения файла с потока обработки в виде метода
        self.handler.file_sending.connect(self.receive)
        self.handler.start()  # Запуск потока
Example #15
0
 def client_handler_thread(self, clientsocket, address):
     """
     Sends the client id assigned to this clientsocket and
     Creates a new ClientHandler object
     See also ClientHandler Class
     :param clientsocket:
     :param address:
     :return: a client handler object.
     """
     #id = address[1]
     #self.send_client_id(clientsocket, id)
     #TODO: create a new client handler object and return it
     client_id = address[1]
     self.client = ClientHandler(self, clientsocket, address)
     self.client.run()
     self.clients[self.client.client_id] = self.client
     return self.client
    def client_handler_thread(self, clientsocket, address):
        # create the client handler
        client_handler = ClientHandler(self, clientsocket, address)

        # init the CH
        client_handler.init()

        try:
            # run the main logic
            client_handler.run()
        except EOFError as err:
            client_id = client_handler.client_id
            print(
                "(x) Client Handler Thread Error --> Client ({name}:{client_id}) left abruptly"
                .format(name=self.names[client_id], client_id=client_id))
            client_handler.delete_client_data()
        except Exception as err:
            print("(x) Client Handler Thread Error --> {err}".format(err=err))
            client_handler.delete_client_data()
Example #17
0
def host_detail(request, host_id):
    client_handler = ClientHandler()
    client_config = client_handler.get_configs(host_id)
    service_name_list = client_config['services'].keys()
    service_name_dic = {}
    for s in models.Service.objects.filter(name__in=service_name_list):
        service_name_dic[s.name] = {
            'has_sub_service': s.has_sub_service,
        }
        if s.has_sub_service:
            redis_key = 'StatusData_%s_%s_%s' % (host_id, s.name, 'latest')
            sub_data = REDIS_OBJ.lrange(redis_key, -1, -1)
            data_point, time_stamp = json.loads(sub_data[0])
            service_name_dic[
                s.name]['sub_services'] = data_point['data'].keys()

    host_obj = models.Host.objects.get(id=host_id)
    return render(request, 'host_detail.html', {
        "host_obj": host_obj,
        "service_name_dic": service_name_dic
    })
Example #18
0
    def client_handler_thread(self, clientsocket, address):
        """
        Sends the client id assigned to this clientsocket and
        Creates a new ClientHandler object
        See also ClientHandler Class
        :param clientsocket:
        :param address:
        :return: a client handler object.
        """
        #TODO: create a new client handler object and return it
        ch_object = ClientHandler(self, clientsocket, address)
        lock = threading.Lock()

        try:
            lock.acquire()
            ch_object.startHandler()
            lock.release()
        except Exception:
            clientsocket.close()

        return ch_object
Example #19
0
    async def handle_client(self, websocket, name):
        while True:
            await asyncio.sleep(1)
            try:
                handler = ClientHandler(self, name, websocket)
                await handler.gather_request()
                await self.device_handler.get_and_send_passive_data(name)

            except Exception as e:
                print(e)
                del self.devices[name]
                del self.devices_type[name]
                break
Example #20
0
 def client_handler_thread(self, clientsocket, address):
     """
     Sends the client id assigned to this clientsocket and
     Creates a new ClientHandler object
     See also ClientHandler Class
     :param clientsocket:
     :param address:
     :return: a client handler object.
     """
     # threading event
     ready = Event()
     # create a new client handler object and return it
     # inits all the components in client handler object
     # self is the server instance
     client_handler = ClientHandler(ready, self, clientsocket, address)
     # adds the client handler object to the list of all the clients objects created by this server.
     # key: client id, value: client handler
     # assumes dict was initialized in class constructor
     self.clients[client_handler.client_id] = client_handler
     # start client handler engine when it is ready
     ready.wait()
     client_handler.run()
     return client_handler
Example #21
0
def start(listener):
    while True:
        try:
            connection = listener.accept_connections(ACCEPT_TIMEOUT)
            if connection != None:
                client_handlers[str(connection)] = ClientHandler(connection)
        except Exception as e:
            print("Fatal error: " + e.message)
            break
        # For now, the only way to shutdown the server is by Ctrl-C key interrupt.
        except KeyboardInterrupt:
            print("Shutting down...")
            break

    for handler in client_handlers.values():
        handler.close()

    listener.close()
async def test_client_handler_register(user_svc, file_svc):
    mock_client = MagicMock()
    raw_msg = bytes(
        '{"username": "******", "password": "******", '
        '"filename": "", "type": "user_register"}', "utf-8")

    mock_client.__aiter__.return_value = [raw_msg]
    mock_client.return_value.send.return_value = Future()
    mock_client.return_value.send.return_value.set_result("123")
    user_svc.return_value.try_reg_user.return_value = True
    MagicMock.__await__ = lambda x: async_magic().__await__()

    user_svc_instance = user_svc.return_value()
    file_svc_instance = file_svc.return_value()
    client_handler = ClientHandler(user_svc_instance, file_svc_instance)

    await client_handler.handle_client(mock_client, None)
    response = mock_client.send.call_args.args[0]

    assert json.loads(response)["success"] is True
Example #23
0
    def __init__(self,
                 user_agent,
                 display_dimensions=None,
                 stringio=None,
                 io=None):
        """
        if display_dimmensions tuple(width, height, dpi) is set
        it will overwrite respective values taken from broo
        """
        self.ua = user_agent
        self.pf = PropertiesFetcher()
        self.capabilities = self.pf.load_capabilities(user_agent=user_agent)
        if not display_dimensions:
            display_dimensions = self.pf.get_display_dimensions(
                self.capabilities)
        self.width = int(display_dimensions[0])
        self.height = int(display_dimensions[1])

        cef.Initialize(self.application_settings(),
                       self.cli_switches(user_agent))
        windowInfo = cef.WindowInfo()
        windowInfo.SetAsOffscreen(0)

        self.browser = cef.CreateBrowserSync(windowInfo,
                                             self.browser_settings())
        self.client_handler = ClientHandler(self.browser, self.width,
                                            self.height, io)
        self.browser.SetClientHandler(self.client_handler)

        # js binding
        jsBindings = cef.JavascriptBindings(bindToFrames=False,
                                            bindToPopups=False)
        jsBindings.SetObject("python", BindObject(stringio))
        self.browser.SetJavascriptBindings(jsBindings)
        self.browser.javascriptBindings.Rebind()
        # end jsbinding

        self.browser.SendFocusEvent(True)
async def test_client_handler_unauthorized(user_svc, file_svc):
    mock_client = MagicMock()
    raw_msg = bytes(
        '{"username": "******", "password": "******", '
        '"filename": "xyz", "type": "file_request"}', "utf-8")
    mock_client.__aiter__.return_value = [raw_msg]
    mock_client.return_value.send.return_value = Future()
    mock_client.return_value.send.return_value.set_result("123")
    user_svc.auth_user.return_value = False
    MagicMock.__await__ = lambda x: async_magic().__await__()

    user_svc_instance = user_svc.return_value()
    user_svc_instance.auth_user.return_value = False
    file_svc_instance = file_svc.return_value()
    client_handler = ClientHandler(user_svc_instance, file_svc_instance)
    client_handler.active_authors.append({
        "connection": mock_client,
        "current_file": None
    })

    await client_handler.handle_client(mock_client, None)
    response = mock_client.send.call_args.args[0]

    assert json.loads(response)["success"] is False
Example #25
0
 def start(self):
     clients = []
     try:
         while True:
             client_socket = None
             print "waiting clients..."
             client_socket, client_addr = self.__s.accept()
             c = ClientHandler(client_socket, client_addr)
             c.set_sessions(self.sess_names)
             clients.append(c)
             c.start()
     except KeyboardInterrupt:
         print "Ctrl+C"
         self.__s.close()
     finally:
         if client_socket != None:
             client_socket.close()
         self.__s.close()
     self.__s.close()
     map(lambda x: x.join(), clients)
Example #26
0
import os

from client_handler import ClientHandler
from constants.input_options import InputOptions


if __name__ == "__main__":
    client = ClientHandler()
    option = -1

    while option != InputOptions.EXIT:
        print("---------------------------")
        print("Opções\n")
        print("{}) Enviar mensagem".format(InputOptions.ECHO))
        print("{}) Listar mensagens".format(InputOptions.LIST))
        print("{}) Sair".format(InputOptions.EXIT))
        print("---------------------------")

        try:
            option = int(input('Escolha uma opção: '))

            if option == InputOptions.ECHO:
                os.system('clear')
                message = input('Escreva sua mensagem: ')
                client.echo(message)

            elif option == InputOptions.LIST:
                os.system('clear')
                messages = client.get_messages()
                print('Listando Mensagens: {}'.format(messages))
Example #27
0
def main():
    run = True
    n = ClientHandler()
    """
    ad = udpc()
    t = threading.Thread(
        target=ad.start_video,
        args=()
    )
    t.start()"""

    p = n.getP()
    minutes = 0
    seconds = 60
    dt = 0
    start_timer = False
    ended = False

    clock = pygame.time.Clock()
    game = None

    while not ended:
        clock.tick(60)
        gp1 = None
        gp2 = None
        gb = None
        try:
            if game:
                if game.getPlayer(
                        p.number).hasTheBall() or game.ballIsRolling():
                    game = n.send((p, game.ball))
                else:
                    if p.goals != game.getPlayer(p.number).getGoals():
                        p.goals = game.getPlayer(p.number).getGoals()
                        game = n.send((p, game.ball))
                    else:
                        p.goals = game.getPlayer(p.number).getGoals()
                        game = n.send(p)
            else:
                game = n.send(p)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                    n.send("disconnect")
                    pygame.quit()

            if game.connected():
                if p.number == 1:
                    gp1 = GrahicsPlayer(p)
                    gp2 = GrahicsPlayer(game.getPlayer2())
                else:
                    gp2 = GrahicsPlayer(p)
                    gp1 = GrahicsPlayer(game.getPlayer1())

                seconds -= dt
                if seconds <= 0:
                    if minutes <= 0 and seconds <= 0:
                        ended = True
                        break
                    else:
                        seconds = 60
                        minutes -= 0
                        period = "2nd Half"
                        game.reset_positions()

                gb = GraphicBall(game.getBall())
                p.move()
            redrawWindow(win, game, gp1, gp2, gb, (minutes, seconds))
            dt = clock.tick(60) / 1000

        except Exception as e:
            print(e)
            break

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
        show_summary(game)
Example #28
0
 def thread_client(self, clienthandler, addr):
     clienthandler = ClientHandler(self, clienthandler, addr)
     data = clienthandler.process_client_data()
     """
Example #29
0
 def thread_client(self, clienthandler, addr):
     # init the client handler object
     c = ClientHandler(self, clienthandler, addr)
     c.process_client_data()
Example #30
0
class Client(QtWidgets.QWidget):
    handler: ClientHandler
    to_send: socket.socket

    # Конструктор: построение визуальных компонентов формы
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        # Задание имени файла
        self.setWindowTitle('Клиент передачи файлов')
        # Задание фиксированных размеров окна
        self.setFixedSize(510, 120)
        # Текстовое поле пути
        self.path = QtWidgets.QLineEdit()
        self.path.setAlignment(QtCore.Qt.AlignCenter)
        self.path.setPlaceholderText('Путь к файлу')
        # Кнопка выбора файла
        self.browse_button = QtWidgets.QPushButton('Выбрать файл')
        # Контейнер компонент, связанных с выбором файла
        self.path_box = QtWidgets.QHBoxLayout()
        self.path_box.addWidget(self.path)
        self.path_box.addWidget(self.browse_button)
        # Текстовое поле адреса
        self.host = QtWidgets.QLineEdit()
        self.host.setMinimumWidth(150)
        self.host.setPlaceholderText('Хост')
        self.host.setAlignment(QtCore.Qt.AlignCenter)
        self.host.setText(socket.gethostname())
        # Числовое поле порта
        self.port = QtWidgets.QSpinBox()
        self.port.setMaximum(2**16)
        self.port.setMinimum(1)
        self.port.setValue(8888)
        self.port.setMaximumWidth(100)
        # Кнопки подключения и отключения от сервера
        self.connection_button = QtWidgets.QPushButton('Подключение')
        self.disconnection_button = QtWidgets.QPushButton('Отключение')
        # Контейнер подключения
        self.connection_box = QtWidgets.QHBoxLayout()
        self.connection_box.addWidget(self.host)
        self.connection_box.addWidget(self.port)
        self.connection_box.addWidget(self.connection_button)
        self.connection_box.addWidget(self.disconnection_button)
        # Кнопка отправки сообщения
        self.send_button = QtWidgets.QPushButton('Отправить')
        # Фоновый контейнер
        self.central_layout = QtWidgets.QVBoxLayout()
        self.central_layout.addLayout(self.path_box)
        self.central_layout.addLayout(self.connection_box)
        self.central_layout.addWidget(self.send_button)
        # Задания фокуса для окна
        self.setFocus()
        self.setLayout(self.central_layout)
        self.block_controls(False)

        # Задание обработок нажатия клавиш
        self.browse_button.clicked.connect(self.browse)
        self.connection_button.clicked.connect(self.connection)
        self.disconnection_button.clicked.connect(self.disconnection)

    # Блокировка/разблокировка компонент, в зависимости от состояния подключения
    def block_controls(self, connected):
        self.connection_button.setDisabled(connected)
        self.host.setDisabled(connected)
        self.port.setDisabled(connected)

        self.disconnection_button.setEnabled(connected)
        self.send_button.setEnabled(connected)

    # Выбор файла
    def browse(self):
        # Открытие диалогового окна, получение адреса
        selection = QtWidgets.QFileDialog.getOpenFileUrl(parent=self,
                                                         caption='Выбор файла',
                                                         filter='All (*)')
        file_path = selection[0].toLocalFile()
        # Запись в строку выбранного пути файла
        self.path.setText(file_path)

    # Соединение с сервером
    def connection(self):
        self.block_controls(True)

        # Инициализация потока, работающего с сокетами
        self.handler = ClientHandler(
            host=self.host.text(
            ),  # Передача параметров хоста (с текстового поля)
            port=self.port.value()  # Передача параметров порта
        )
        # Задание событию нажатия кнопки "Отправить" действия по отправке файла
        self.handler.for_receive.connect(
            lambda sock: self.send_button.clicked.connect(
                partial(self.send, sock=sock)))
        # Задание событию получения файла с потока обработки в виде метода
        self.handler.file_sending.connect(self.receive)
        self.handler.start()  # Запуск потока

    # Отсоединение
    def disconnection(self):
        self.block_controls(False)
        # Убийство потока с сокетом
        self.handler.terminate()

    # Отправка файла
    def send(self, sock):
        path = self.path.text()  # Получение пути файла с текстового поля
        file_name = os.path.basename(path)  # Извлечение имени файла с пути
        file_content = open(
            path, 'rb').read()  # Чтение выбранного файла в бинарном виде
        # Преобразование кортежа из имени и содержания файла в массив байт
        message = pickle.dumps((file_name, file_content))
        # Отправка сообщения (с характерной обёрткой) на сервер
        # Обёртка нужна, чтобы определить полноту полученного сообщения (оно отправляется по частям по 1024 байт)
        sock.send(b'<begin>' + message + b'<end>')

    # Получение файла
    @staticmethod
    def receive(file):
        yes = 16384  # Код, возвращаемый диалоговым окном при положительном ответе пользователя
        confirm = QtWidgets.QMessageBox.question(
            None,
            'Подтверждение сохранения файла',
            'Был получен новый файл. Вы желаете его сохранить?',
            buttons=QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
            defaultButton=QtWidgets.QMessageBox.Yes)
        if confirm == yes:
            name, content = pickle.loads(
                file
            )  # Извлечение имени и содержания файла и полученного сообщения
            dia = QtWidgets.QFileDialog()  # Инициализация диалога
            dia.setDefaultSuffix(
                name.split('.')
                [1])  # Подписание расширения получаемого файла при сохранении
            dia.setAcceptMode(QtWidgets.QFileDialog.AcceptSave
                              )  # Вид диалогового окна - сохранение
            dia.setLabelText(QtWidgets.QFileDialog.FileType,
                             name.split('.')[1])  #
            if dia.exec():  # Если результат диалогового окна непустой
                save_path = dia.selectedFiles()[
                    0]  # Получение пути выбранного файла
                file = open(save_path,
                            'wb')  # Открытие (создание) файла в бинарном виде
                file.write(content)  # Запись в файл содержимого
                file.close()  # Прекращение работы с файлом