Пример #1
0
    def __init__(self, main_window, on_connection, log):
        super().__init__(main_window)
        self.log = log.getChild('TCP')

        self.log.info('Initializing')

        self.main_window = main_window
        self.on_connection = on_connection

        self.host, self.port = CONFIG.listen_address
        self.host = QHostAddress(self.host)
        self.benchmark = CONFIG['benchmark']
        self.conn_count = 0

        self.threads = []
Пример #2
0
    def start(self):
        if self.logger_name:
            self.logger = logging.getLogger(self.logger_name)  # noqa
        else:
            self.logger = logging.getLogger(self.__class__.__name__)  # noqa
        self.data = {"size_left": 0, "data": b""}  # noqa
        self.tcpSocket = QTcpSocket(self)  # noqa

        self.tcpSocket.setObjectName("qclient_socket")
        QMetaObject.connectSlotsByName(self)
        self.tcpSocket.setSocketOption(QAbstractSocket.KeepAliveOption, 1)
        self.tcpSocket.connectToHost(QHostAddress(self.ip), self.port,
                                     QIODevice.ReadWrite)
        if not self.tcpSocket.waitForConnected(3000):
            self.failed_to_connect.emit(self.ip, self.port)
            self.tcpSocket.disconnectFromHost()
            self.tcpSocket.close()
            self.logger.error("Failed to connect to {}:{}".format(
                self.ip, self.port))
            return

        self.close_signal.connect(self.close, Qt.BlockingQueuedConnection)
        self.write_signal.connect(self._write)
        self.connect_signal.connect(self._connectTo)
        self.disconnect_signal.connect(self._disconnect)
        self.reconnect_signal.connect(self._reconnect)
Пример #3
0
    def __init__(self, main_window, on_connection, log):
        super().__init__(main_window)
        self.log = log.getChild('TCP')

        self.log.info('Initializing')

        self.main_window = main_window
        self.on_connection = on_connection

        self.host, self.port = CONFIG.listen_address
        self.host = QHostAddress(self.host)
        self.benchmark = CONFIG['benchmark']
        self.conn_count = 0

        self.threads = []
        QNetworkProxyFactory.setUseSystemConfiguration(
            CONFIG['use_system_proxy'])
Пример #4
0
    def start(self):
        self.server = QTcpServer()
        if self.server.listen(QHostAddress(''), 56682):
            print('server: listening ...')
            self.server.newConnection.connect(self.on_new_connection)
        else:
            print('server: failed to start tcp server')
            self.server.close()

        return self
Пример #5
0
    def start(self, ip: str, port: int):
        """Start server."""
        if self.__handlerClass:
            ip = QHostAddress(ip)
            self.__ip = ip
            self.__port = port
            self.__handler = self.__handlerClass()
            self.__handler_thread = QThread()
            self.__handler.moveToThread(self.__handler_thread)

            self.__handler.connected.connect(
                self.__on_handler_successful_connection)
            self.__handler.message.connect(self.__on_handler_device_message)
            self.__handler.error.connect(self.__on_handler_device_error)
            self.__handler.disconnected.connect(
                self.__on_handler_device_disconnected)
            self.__handler.closed.connect(self.on_closed)

            self.__handler_thread.started.connect(self.__handler.start)
            self.__handler.started.connect(self.__setup_server)
            self.__handler_thread.start()
        else:
            raise Exception("Handler class not set!")
Пример #6
0
class LogServer(QTcpServer):
    def __init__(self, main_window, on_connection, log):
        super().__init__(main_window)
        self.log = log.getChild('TCP')

        self.log.info('Initializing')

        self.main_window = main_window
        self.on_connection = on_connection

        self.host, self.port = CONFIG.listen_address
        self.host = QHostAddress(self.host)
        self.benchmark = CONFIG['benchmark']
        self.conn_count = 0

        self.threads = []
        QNetworkProxyFactory.setUseSystemConfiguration(
            CONFIG['use_system_proxy'])

    def start(self):
        self.log.info('Starting the server')
        if self.benchmark:
            self.log.debug('Starting a benchmark connection')
            new_conn = BenchmarkConnection(self, None, "benchmark", self.log)
            new_conn.finished.connect(new_conn.deleteLater)
            new_conn.connection_finished.connect(self.cleanup_connection)
            self.on_connection(new_conn, -1)
            self.threads.append(new_conn)
            new_conn.start()

        result = self.listen(self.host, self.port)
        if not result:
            err_string = self.errorString()
            show_critical_dialog(self.main_window,
                                 'Error while starting the server', err_string)
        else:
            address = "{}:{}".format(self.host.toString(), self.port)
            self.main_window.set_status(
                'Server is listening on {}...'.format(address))

    def incomingConnection(self, socketDescriptor):
        self.conn_count += 1
        conn_id = str(self.conn_count)
        self.log.info('New connection id={}'.format(conn_id))
        new_conn = LogConnection(self, socketDescriptor, conn_id, self.log)

        self.on_connection(new_conn, conn_id)
        new_conn.setObjectName(conn_id)
        new_conn.finished.connect(new_conn.deleteLater)
        new_conn.connection_finished.connect(self.cleanup_connection)
        new_conn.start()
        self.threads.append(new_conn)

    def close_server(self):
        self.log.debug('Closing the server')
        self.main_window.set_status('Stopping the server...')
        self.close()
        for thread in self.threads.copy():
            thread.requestInterruption()
        self.wait_connections_stopped()
        self.main_window.set_status('Server has stopped')

    def wait_connections_stopped(self):
        self.log.debug('Waiting for {} connections threads to stop'.format(
            len(self.threads)))
        for thread in self.threads.copy():
            try:
                if not thread.wait(1500):
                    # @Hmm: sometimes wait() complains about QThread waiting on itself
                    self.log.debug(
                        "Thread \"{}\" didn't stop in time, exiting".format(
                            thread))
                    return
            except RuntimeError:  # happens when thread has been deleted before we got to it
                self.log.debug(
                    'Thread {} has been deleted already'.format(thread))
        self.log.debug('Waiting for connections has stopped')

    def cleanup_connection(self, connection):
        try:
            self.threads.remove(connection)
        except Exception:
            self.log.error(
                'Double delete on connection: {}'.format(connection),
                exc_info=True)
            return