Exemplo n.º 1
0
    def __init__(self, sock_type='TCP Client', ip='127.0.0.1', port=2007):
        '''打开网络设备,建立连接
        ## sock_type:
           - 'TCP Client'
           - 'TCP Server'
           - 'UDP'
        '''
        self.sock_type = sock_type
        # self.ip = ip
        self.port = port

        if sock_type == 'TCP Client':
            tcp_client = QTcpSocket()
            tcp_client.connectToHost(ip, port)
            self.sock = tcp_client
        elif sock_type == 'TCP Server':
            tcp_server = QTcpServer()
            tcp_server.listen(QHostAddress(ip), port)
            self.sock = tcp_server

        elif sock_type == 'UDP':
            udp = QUdpSocket()
            udp.bind(QHostAddress(ip), port)
            self.sock = udp
        else:
            print('Unkonw sock_type=%r' % sock_type)
Exemplo n.º 2
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)
        self.main = parent
        self.background_tex = QImage("Ground.png")
        self.ups = 60
        self.uc = 0
        self.gamesecond = 0
        self.players_tex = [QImage("panzer_0.png"), QImage("panzer_1.png"), QImage("panzer_2.png")]
        self.explosion_sprites = [QImage("000" + str(i) + ".png") for i in range(1,10)] + [QImage("00"+str(i)+".png") for i in range(10,51)]
        self.players = [Player(self.ups, (0.5, 0.5)),Player(self.ups, (0.7, 0.7))]
        self.controls = [False, False, False, False, False]
        self.controls2 = [False, False, False, False, False]
        self.inputs = [self.controls,self.controls2]

        self.timer = QTimer()
        # Wir richten einen Server ein, zu dem Clients einen Kommunikationskanal
        # öffnen können.
        self.tcpServer = QTcpServer(self)
        # Der Server akzeptiert jeden Client, der auf der angegebenen Port-Nummer
        # sendet.
        self.tcpServer.listen(QHostAddress.Any, 40890)
        # self.tcpServer.listen(QHostAddress('127.0.0.1'), 40890)

        # Falls beim Server eine Verbindungsanfrage von einem Client eingeht,
        # soll die eigene Memberfunktion connectToClient aufgerufen werden.
        self.tcpServer.newConnection.connect(self.connectToClient)
Exemplo n.º 3
0
    def __init__(self):
        super().__init__()
        self.config = Config("config.ini")

        # INIT Controls
        self.wheels = Wheels(self.config.steeringMid, self.config.steeringLeft,
                             self.config.steeringRight)
        self.accelerator = Accelerator(self.config, self)

        self.__initUI()
        self.statusBar().showMessage("Board not connected")

        # Init uds listener
        self._log("Init udp at {}:{}".format(
            get_ip(), self.config.getOption('udp_port')))
        self.udpSocket = QUdpSocket()
        self.udpSocket.setLocalAddress(QHostAddress(get_ip()))
        self.udpSocket.bind(self.config.getOption('udp_port'))
        self.udpSocket.readyRead.connect(self.udpHandler)

        # Init tcp server
        self.tcpServer = QTcpServer(self)
        self._log("Starting TCP at {}:{} ".format(
            get_ip(), str(self.config.getOption('tcp_port'))))
        self.tcpServer.listen(QHostAddress(get_ip()),
                              self.config.getOption('tcp_port'))
        self.tcpServer.newConnection.connect(self.establishBoardConnection)

        self.show()
Exemplo n.º 4
0
class QTServerThread(QWidget):
    server = None
    players = []

    def __init__(self, _parent):
        super().__init__(_parent)
        self.setLayout(QHBoxLayout())
        self.server = QTcpServer(self)
        if self.server.listen(port=4223) is False:
            print("Error starting the server!")
            return
        self.server.newConnection.connect(self.handleNewConnection)

    def getIDFromSocket(self, socket):
        ipadd = socket.peerAddress().toString()
        splited = ipadd.split(".")
        return int(splited[len(splited)-1])

    @pyqtSlot()
    def handleNewConnection(self):
        newSock = self.server.nextPendingConnection()
        if(newSock is not None):
            newID = self.getIDFromSocket(newSock)
            for player in self.players:
                if self.getIDFromSocket(player.client.sock) == newID:
                    player.client.attachSock(newSock)
                    return

            newPlayer = GPlayer(newSock, newID)
            self.players.append(newPlayer)
            self.layout().addWidget(newPlayer)
Exemplo n.º 5
0
 def __init__(self):
     super().__init__()
     self.tcpServer = QTcpServer(self)
     address = QHostAddress('127.0.0.1')
     self.tcpServer.listen(address, PORT)
     self.tcpServer.newConnection.connect(self.dealCommunication)
     print("[SERVER] Listening on port-", PORT, "...")
Exemplo n.º 6
0
class Server(QObject):
    def __init__(self, parent: QObject = None):
        super().__init__(parent)
        self.m_server = QTcpServer()
        self.m_server.newConnection.connect(self.handleNewConnection)

    @pyqtSlot()
    def run(self):
        if not self.m_server.listen(QHostAddress.LocalHost, 5555):
            print(
                f"Could not start the server -> http/proxy authentication dialog will not work. Error:{self.m_server.errorString()}"
            )

    @pyqtSlot()
    def handleNewConnection(self):
        socket = self.m_server.nextPendingConnection()
        socket.disconnected.connect(socket.deleteLater)
        socket.readyRead.connect(self.handleReadReady)

    @pyqtSlot()
    def handleReadReady(self):
        socket = self.sender()
        assert socket
        msg = socket.readAll()
        if msg.contains(b"OPEN_AUTH"):
            socket.write(b"HTTP/1.1 401 Unauthorized\nWWW-Authenticate: "
                         b'Basic realm="Very Restricted Area"\r\n\r\n')
        if msg.contains(b"OPEN_PROXY"):
            socket.write(
                b"HTTP/1.1 407 Proxy Auth Required\nProxy-Authenticate: "
                b'Basic realm="Proxy requires authentication"\r\n\r\n')
Exemplo n.º 7
0
class cServer(QTcpSocket):
    finished = QtCore.pyqtSignal()
    newData = QtCore.pyqtSignal(str)
    running = False
    def __init__(self):
        super().__init__()
        self.tcpServer = QTcpServer(self)
        PORT = 9999
        address = QHostAddress('127.0.0.1')
        self.tcpServer.listen(address, PORT)
        self.tcpServer.newConnection.connect(self.dealCommunication)
        print("[SERVER] Listening on port-", PORT, "...")

    def dealCommunication(self):
        print("[SERVER] Client is connecting...")
        client = self.tcpServer.nextPendingConnection()
        msg = str(client.readAll(),encoding='utf-8')
        self.newData.emit(msg)

    def run(self):
        self.running = True
        while self.running:
            QtCore.QCoreApplication.processEvents()
        print("[SERVER] Terminated!")

    def stop(self):
        self.running = False
        self.finished.emit()
Exemplo n.º 8
0
 def __init__(self):
     self.local_server = QTcpServer()
     self.local_server.newConnection.connect(self._handle_connection)
     increment = 0
     while (available := self.local_server.listen(port=DEFAULT_LOCAL_PORT +
                                                  increment)) is False:
         increment += 1
Exemplo n.º 9
0
    def __init__(self, parent=None):
        super(ListenPipe, self).__init__(parent=parent)

        self.tcpServer = QTcpServer()
        self.socketClients = []

        self.tcpServer.newConnection.connect(self.on_newconnection)
class TcpServer():
    def __init__(self):
        self.tcp_server = QTcpServer()
        self.tcp_server.listen(QHostAddress(SERVER_ADDRESS), SERVER_PORT)
        self.tcp_server.newConnection.connect(self.connect_client)
        self.clients = []

    def connect_client(self):
        client_socket = self.tcp_server.nextPendingConnection()
        self.clients.append(client_socket)
        client_socket.readyRead.connect(self.read_data)

    def read_data(self):
        for client_id, client_socket in enumerate(self.clients):
            if client_socket.bytesAvailable() > 0:
                stream = QDataStream(client_socket)
                stream.setVersion(QDataStream.Qt_5_9)
                stream.readUInt32()
                client_data = stream.readQString()
                self.return_data_to_clients(client_id, client_data)

    def return_data_to_clients(self, client_id, data):
        for client_socket in self.clients:
            return_data_string = 'Client {} sent: {}'.format(client_id, data)
            data_byte_array = QByteArray()
            stream = QDataStream(data_byte_array, QIODevice.WriteOnly)
            stream.setVersion(QDataStream.Qt_5_9)
            stream.writeUInt32(0)
            stream.writeQString(return_data_string)
            client_socket.write(data_byte_array)
class MainApp(QCoreApplication):
    def __init__(self, argv):
        super().__init__(argv)
        self.server = QTcpServer(self)
        self.server.setMaxPendingConnections(1)
        self.server.newConnection.connect(self.onNewConnection)
        self.server.listen(QHostAddress.Any, 6666)
        self.client = QTcpSocket(self)
        self.cap = cv2.VideoCapture(0)

    @pyqtSlot()
    def onNewConnection(self):
        self.client = self.server.nextPendingConnection()
        self.client.disconnected.connect(self.onClientDisconnected)
        self.client.readyRead.connect(self.onClientReadyRead)
        print('connected')

    @pyqtSlot()
    def onClientDisconnected(self):
        print('disconnected')

    @pyqtSlot()
    def onClientReadyRead(self):
        while self.client.canReadLine():
            line = self.client.readLine()[:-1]

            if 'get' == line:
                ret, frame = self.cap.read()
                data = cv2.imencode('.jpg', frame)[1]
                self.client.writeData((str(len(data)) + '\n').encode())
                self.client.writeData(data)
Exemplo n.º 12
0
class Server(QDialog):
    def __init__(self):
        super().__init__()
        self.tcpServer = None
        self.signals = ServerSignals()
        self.clientConnection = None

    def sessionOpened(self):
        self.tcpServer = QTcpServer(self)
        PORT = 65432
        address = QHostAddress('127.0.0.1')
        if not self.tcpServer.listen(address, PORT):
            print("cant listen!")
            self.close()
            return
        self.tcpServer.newConnection.connect(self.dealCommunication)

    @pyqtSlot()
    def dealCommunication(self):
        # Get a QTcpSocket from the QTcpServer
        self.clientConnection = self.tcpServer.nextPendingConnection()

        # wait until the connection is ready to read
        self.clientConnection.waitForReadyRead()
        # read incomming data
        instr = self.clientConnection.readAll()

        # raise signal with message
        tomaingui = str(instr, encoding='utf-8')
        self.signals.msg.emit(tomaingui)

    # def sendtoclient(self, msg):
    #     # OLD Might be deleted in next version
    #
    #     # instantiate a QByteArray
    #     block = QByteArray()
    #     out = QDataStream(block, QIODevice.ReadWrite)
    #     out.setVersion(QDataStream.Qt_5_0)
    #
    #     # this is the message we will send it could come from a widget.
    #     message = msg + '\n'
    #     # message = msg
    #     message = bytes(message, encoding='utf-8')
    #     # now use the QDataStream and write the byte array to it.
    #     out.writeString(message)
    #     out.device().seek(0)
    #     out.writeUInt16(block.size() - 2)
    #
    #     # get the connection ready for clean up
    #     self.clientConnection.disconnected.connect(self.clientConnection.deleteLater)
    #     # now send the QByteArray.
    #     self.clientConnection.write(block)
    #     # now disconnect connection.
    #     self.clientConnection.disconnectFromHost()

    def sendeasy(self, msg):
        message = msg + '\n'
        out = bytes(message, 'utf-8')
        self.clientConnection.write(out)
        self.clientConnection.disconnectFromHost()
 def __init__(self, argv):
     super().__init__(argv)
     self.server = QTcpServer(self)
     self.server.setMaxPendingConnections(1)
     self.server.newConnection.connect(self.onNewConnection)
     self.server.listen(QHostAddress.Any, 6666)
     self.client = QTcpSocket(self)
     self.cap = cv2.VideoCapture(0)
Exemplo n.º 14
0
 def __init__(self, _parent):
     super().__init__(_parent)
     self.setLayout(QHBoxLayout())
     self.server = QTcpServer(self)
     if self.server.listen(port=4223) is False:
         print("Error starting the server!")
         return
     self.server.newConnection.connect(self.handleNewConnection)
Exemplo n.º 15
0
    def openController(self):
        self.isUp = True
        self.ui.btClose.setText('关机')
        self.timer.start(self.req_sta_inter)

        self.server = QTcpServer()
        self.server.listen(self.serverIP, self.port)
        self.server.newConnection.connect(self.addClient2List)
class Server(QWidget):
    def __init__(self, model, prediction, vocabulary):
        super(Server, self).__init__()
        self.model = model
        self.prediction = prediction
        self.vocabulary = vocabulary
        self.resize(500, 450)

        # 1
        self.browser = QTextBrowser(self)

        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.browser)
        self.setLayout(self.v_layout)

        # 2
        self.server = QTcpServer(self)
        if not self.server.listen(QHostAddress.LocalHost, 8080):
            self.browser.append(self.server.errorString())
        self.server.newConnection.connect(self.new_socket_slot)

    def new_socket_slot(self):
        sock = self.server.nextPendingConnection()

        peer_address = sock.peerAddress().toString()
        peer_port = sock.peerPort()
        news = 'Connected with address {}, port{}'.format(
            peer_address, str(peer_port))
        self.browser.append(news)

        sock.readyRead.connect(lambda: self.read_data_slot(sock))
        sock.disconnected.connect(lambda: self.disconnected_slot(sock))

    # 3
    def read_data_slot(self, sock):
        while sock.bytesAvailable():
            datagram = sock.read(sock.bytesAvailable())
            message = datagram.decode()
            answer = self.get_answer(message).encode()
            sock.write(bytes(answer))

    def get_answer(self, message):
        sentence = pre_dosegment(message)
        sentence = ' '.join(sentence)
        prediction1 = self.model.test(str(sentence), self.vocabulary)
        query = match_question(prediction1, str(message))
        answer = self.prediction.run(query, prediction1)
        return answer

    # 4
    def disconnected_slot(self, sock):
        peer_address = sock.peerAddress().toString()
        peer_port = sock.peerPort()
        news = 'Disconnected with address {}, port {}'.format(
            peer_address, str(peer_port))
        self.browser.append(news)

        sock.close()
Exemplo n.º 17
0
 def sessionOpened(self):
     self.tcpServer = QTcpServer(self)
     PORT = 65432
     address = QHostAddress('127.0.0.1')
     if not self.tcpServer.listen(address, PORT):
         print("cant listen!")
         self.close()
         return
     self.tcpServer.newConnection.connect(self.dealCommunication)
Exemplo n.º 18
0
    def __init__(self):
        """Constructor."""
        QObject.__init__(self)

        self.__tcpServer = QTcpServer()

        self.__active_sockets = []

        self.__tcpServer.newConnection.connect(self.__new_connection)
Exemplo n.º 19
0
    def __init__(self, parent=None):
        super(Server, self).__init__(parent)
        self.proxy_server = QTcpServer(self)
        self.proxy_server.listen(QHostAddress.Any, 8000)
        self.proxy_server.newConnection.connect(self.manage_request)

        if self.debug:
            self.log.write('Server running on localhost port %s\n\n' %
                           self.port())
Exemplo n.º 20
0
    def sessionOpened(self, port=8000):
        self.tcpServer = QTcpServer(self)
        address = QHostAddress('127.0.0.1')
        if not self.tcpServer.listen(address, port):
            print("cant listen!")
            self.close()
            return

        print("Server Ready")
        self.tcpServer.newConnection.connect(self.dealCommunication)
Exemplo n.º 21
0
 def sessionOpened(self):
     self.tcpServer = QTcpServer(self)
     PORT = 8000
     address = QHostAddress(
         self.ip)  # e.g. use your server ip 192.144.178.26
     if not self.tcpServer.listen(address, PORT):
         print("cant listen!")
         self.close()
         return
     self.tcpServer.newConnection.connect(self.serverInputCommunication)
Exemplo n.º 22
0
    def openRoom(self):
        self.ui.openBtn.setText('Close Chat Room')
        self.isUp = True
        self.ui.serverIPLineEdit.setEnabled(False)
        self.ui.portLineEdit.setEnabled(False)

        self.tcpServer = QTcpServer()
        self.tcpServer.listen(self.serverIP, self.port)
        msg = '[*] Server is listening on {}:{} ........'.format(self.serverIP.toString(), self.port)
        self.ui.contentListWidget.addItem(msg)
        self.tcpServer.newConnection.connect(self.addClient2List)
Exemplo n.º 23
0
    def __init__(self, port, shell_variables=None):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.tcp_server = QTcpServer()
        self.sockets = []
        self.stack_trace = None
        if not self.tcp_server.listen(port=port):
            self.logger.error("Unable to start code execution socket! Error: %s", self.tcp_server.errorString())
        else:
            connect(self.tcp_server.newConnection, self._on_new_connection)

        self.shell = Console(locals=shell_variables or {}, logger=self.logger)
Exemplo n.º 24
0
    def __init__(self):
        super(TcpServer, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.tcpServer = QTcpServer(self)  #指定父对象自动回收空间 监听套接字
        self.tcpSocket = QTcpSocket(self)  #通信套接字

        self.tcpServer.listen(QHostAddress.Any, 8888)  #any默认绑定当前网卡的所有IP
        self.tcpServer.newConnection.connect(self.handleNewConnection)
        self.ui.sendButton.clicked.connect(self.sendMessage)
        self.ui.closeButton.clicked.connect(self.closeConnect)
Exemplo n.º 25
0
    def __init__(self, parent=None):
        super().__init__(parent)
        # Das Zeichenfeld muss den Focus für KeyPress-Events erhalten.
        self.setFocusPolicy(Qt.StrongFocus)
        # Wir laden eine png-Datei (mit Transparenz) und skalieren das Bild
        # auf die gewünschte Größe.
        self.background_tex = QImage("Ground.png")
        self.players_tex = [
            QImage("panzer_0.png"),
            QImage("panzer_1.png"),
            QImage("panzer_2.png")
        ]
        self.explosion_sprites = [
            QImage("000" + str(i) + ".png") for i in range(1, 10)
        ] + [QImage("00" + str(i) + ".png") for i in range(10, 51)]

        self.main = parent
        self.lebendig = True
        self.alive = False
        self.point = QPoint(0, 0)
        self.pointl = QPoint(0, 0)
        self.balls = []
        self.ballsize = 15
        self.image = QImage('Pacman.png').scaled(100, 100)
        self.x = 100
        self.y = 100
        self.velx = 0
        self.vely = 0
        self.winkel = 0
        self.winkelnext = 0
        self.players = []
        self.score1 = 0
        self.score2 = 0

        self.level_id = 0
        self.wallscoordinates = []
        self.walls = []
        self.wallsbuild = False
        self.run = True
        self.ups = 60
        self.connected = False
        self.timer = QTimer()
        # Wir richten einen Server ein, zu dem Clients einen Kommunikationskanal
        # öffnen können.
        self.tcpServer = QTcpServer(self)
        # Der Server akzeptiert jeden Client, der auf der angegebenen Port-Nummer
        # sendet.
        self.tcpServer.listen(QHostAddress.Any, 40890)
        # self.tcpServer.listen(QHostAddress('127.0.0.1'), 40890)

        # Falls beim Server eine Verbindungsanfrage von einem Client eingeht,
        # soll die eigene Memberfunktion connectToClient aufgerufen werden.
        self.tcpServer.newConnection.connect(self.connectToClient)
Exemplo n.º 26
0
 def openMachine(self):
     self.isUp = True
     self.ui.btCold.setEnabled(True)
     self.ui.btWarm.setEnabled(True)
     self.ui.spRefFre.setEnabled(True)
     self.ui.spSendFre.setEnabled(True)
     self.ui.btClose.setText('关机')
     self.server = QTcpServer()
     self.server.listen(self.serverIP, self.port)
     self.server.newConnection.connect(self.newClient)
     self.sendStateTimer.start(self.sendInterval)
     self.refTableTimer.start(self.refInterval)
Exemplo n.º 27
0
    def __init__(self, parent=None):
        super(DataReceive, self).__init__(parent)
        self.tcpServer = QTcpServer(self)
        if self.tcpServer.listen(QHostAddress("127.0.0.1"), 8890):
            self.tcpServer.newConnection.connect(self.sendMessage)
            self.tcpServerConnection = None
            print('init done')

        self.index = 0
        self.data_size = 0
        self.message = None
        self.image = None
Exemplo n.º 28
0
 def __init__(self, gui):
     SessionManager.__init__(self, gui)
     self.session_type = SessionType.TEACHER
     self.gui = gui
     self.session_ticker = Ticker(self.tickSessionOnce, parent=gui)
     self.simulation_paused_at = None  # pause time if session is paused; None otherwise
     self.server = QTcpServer(gui)
     self.student_socket = None
     self.server.newConnection.connect(self.studentConnects)
     self.aircraft_list = []  # ControlledAircraft list
     self.current_local_weather = None  # initialised by the teaching console on sessionStarted
     self.noACK_traffic_count = 0
Exemplo n.º 29
0
 def runReceiver(self, hostAddress: str):
     if not self.__server:
         self.__server = QTcpServer(self)
         self.__server.acceptError.connect(self.__error)
     if not self.__server.listen(
             QHostAddress(hostAddress),
             self.__serverPort) and not self.isListening():
         print("RECEIVER NOT STARTED", self.__server.errorString())
     else:
         self.__server.newConnection.connect(self.__newConnection)
         self.__incomingConnectionsAddress = hostAddress
         self.__incomingConnectionsPort = self.__serverPort
         print("RECEIVER STARTED")
Exemplo n.º 30
0
 def initServer(self):
     """
     网络设置初始化
     """
     self.tcpPort = 7788
     self.tcpServer = QTcpServer(self)
     self.clientConnection = QTcpSocket(self)
     self.tcpServer.newConnection.connect(self.sendMessage)
     self.serverStatuslabel.setText("请选择要传送的文件")
     self.progressBar.reset()
     self.serverOpenBtn.setEnabled(True)
     self.serverSendBtn.setEnabled(False)
     self.tcpServer.close()
Exemplo n.º 31
0
    def sessionOpened(self):
        if self.networkSession is not None:
            config = self.networkSession.configuration()

            if config.type() == QNetworkConfiguration.UserChoice:
                id = self.networkSession.sessionProperty('UserChoiceConfiguration')
            else:
                id = config.identifier()

            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            settings.setValue('DefaultNetworkConfiguration', id)
            settings.endGroup();

        self.tcpServer = QTcpServer(self)
        if not self.tcpServer.listen():
            QMessageBox.critical(self, "Fortune Server",
                    "Unable to start the server: %s." % self.tcpServer.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.statusLabel.setText("The server is running on\n\nIP: %s\nport %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.tcpServer.serverPort()))
Exemplo n.º 32
0
    def __init__(self, port, shell_variables={}):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.tcp_server = QTcpServer()
        self.sockets = []
        self.stack_trace = None
        if not self.tcp_server.listen(port=port):
            self.logger.error("Unable to start code execution socket! Error: %s", self.tcp_server.errorString())
        else:
            self.tcp_server.newConnection.connect(self._on_new_connection)

        self.shell = Console(locals=shell_variables)
Exemplo n.º 33
0
    def _onPushButton_Openserver_Clicked(self):
        print("start socker at ",self.port)

        if self.serveropened is False:
            #start init qtcpserver
            self.tcpServer = QTcpServer(self)
            address = QHostAddress('0.0.0.0')
            if not self.tcpServer.listen(address, self.port):
                print("cant listen!")
                self.close()
                return
            self.tcpServer.newConnection.connect(self.dealCommunication)
            self.fillActivateIps()
Exemplo n.º 34
0
    class TcpServer(QObject):
        def __init__(self):
            super(TcpServer, self).__init__()
            self.server = QTcpServer()
            self.server.newConnection.connect(self.incomingConnection)

        @pyqtSlot()
        def incomingConnection(self):
            self.client = TcpClient(self.server.nextPendingConnection())
            self.client.parse_data = self.parse_data

        def start(self):
            if self.server.listen(QHostAddress.Any, 8888):
                print "Tcp server started"
            else:
                print "Error starting Tcp server"

        def parse_data(self, data):
            print 'Server: ', str(data).strip()

        def moveToThread(self, target_thread):
            self.server.moveToThread(target_thread)
            super(TcpServer, self).moveToThread(target_thread)
Exemplo n.º 35
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.cam = webcam(640, 480, '/dev/video0')
        self.cam.activate()

        self.statusLabel = QLabel()
        self.quitButton = QPushButton("Quit")
        self.quitButton.setAutoDefault(False)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle('Frame Server')

        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen()
        self.client = None

        ipAddress = ''
        for address in QNetworkInterface.allAddresses():
            if address != QHostAddress.LocalHost and address.toIPv4Address():
                ipAddress = address.toString()
                break

        if len(ipAddress) == 0:
            ipAddress = QHostAddress(QHostAddress.LocalHost).toString()

        self.statusLabel.setText(
            'Address:\t\t{}\nPort:\t\t\t{}'.format(ipAddress, self.tcpServer.serverPort()))

        self.quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.clientConnected)
Exemplo n.º 36
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.tcpServer = QTcpServer()
        self.tcpClient = QTcpSocket()
        self.bytesToWrite = 0
        self.bytesWritten = 0
        self.bytesReceived = 0

        self.clientProgressBar = QProgressBar()
        self.clientStatusLabel = QLabel("Client ready")
        self.serverProgressBar = QProgressBar()
        self.serverStatusLabel = QLabel("Server ready")

        self.startButton = QPushButton("&Start")
        self.quitButton = QPushButton("&Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        self.startButton.clicked.connect(self.start)
        self.quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.acceptConnection)
        self.tcpClient.connected.connect(self.startTransfer)
        self.tcpClient.bytesWritten.connect(self.updateClientProgress)
        self.tcpClient.error.connect(self.displayError)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.clientProgressBar)
        mainLayout.addWidget(self.clientStatusLabel)
        mainLayout.addWidget(self.serverProgressBar)
        mainLayout.addWidget(self.serverStatusLabel)
        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Loopback")
Exemplo n.º 37
0
class Server(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.cam = webcam(640, 480, '/dev/video0')
        self.cam.activate()

        self.statusLabel = QLabel()
        self.quitButton = QPushButton("Quit")
        self.quitButton.setAutoDefault(False)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle('Frame Server')

        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen()
        self.client = None

        ipAddress = ''
        for address in QNetworkInterface.allAddresses():
            if address != QHostAddress.LocalHost and address.toIPv4Address():
                ipAddress = address.toString()
                break

        if len(ipAddress) == 0:
            ipAddress = QHostAddress(QHostAddress.LocalHost).toString()

        self.statusLabel.setText(
            'Address:\t\t{}\nPort:\t\t\t{}'.format(ipAddress, self.tcpServer.serverPort()))

        self.quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.clientConnected)

    def clientConnected(self):
        self.client = self.tcpServer.nextPendingConnection()
        self.client.disconnected.connect(self.client.deleteLater)
        self.client.disconnected.connect(self.clientDisconnected)
        self.client.readyRead.connect(self.sendFrame)
        self.client.readyRead.connect(self.client.readAll)
        self.client.setReadBufferSize(32)
        self.tcpServer.pauseAccepting()

    def clientDisconnected(self):
        self.client = None
        self.tcpServer.resumeAccepting()

    def sendFrame(self):
        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_5_0)

        frame = huffman.encode(self.cam.capture())

        out.writeInt32(len(frame))
        out.writeRawData(frame)

        self.client.write(block)
Exemplo n.º 38
0
class Dialog(QDialog):
    TotalBytes = 50 * 1024 * 1024
    PayloadSize = 65536

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.tcpServer = QTcpServer()
        self.tcpClient = QTcpSocket()
        self.bytesToWrite = 0
        self.bytesWritten = 0
        self.bytesReceived = 0

        self.clientProgressBar = QProgressBar()
        self.clientStatusLabel = QLabel("Client ready")
        self.serverProgressBar = QProgressBar()
        self.serverStatusLabel = QLabel("Server ready")

        self.startButton = QPushButton("&Start")
        self.quitButton = QPushButton("&Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.startButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole)

        self.startButton.clicked.connect(self.start)
        self.quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.acceptConnection)
        self.tcpClient.connected.connect(self.startTransfer)
        self.tcpClient.bytesWritten.connect(self.updateClientProgress)
        self.tcpClient.error.connect(self.displayError)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.clientProgressBar)
        mainLayout.addWidget(self.clientStatusLabel)
        mainLayout.addWidget(self.serverProgressBar)
        mainLayout.addWidget(self.serverStatusLabel)
        mainLayout.addStretch(1)
        mainLayout.addSpacing(10)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Loopback")

    def start(self):
        self.startButton.setEnabled(False)

        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.bytesWritten = 0
        self.bytesReceived = 0

        while not self.tcpServer.isListening() and not self.tcpServer.listen():
            ret = QMessageBox.critical(self, "Loopback",
                    "Unable to start the test: %s." % self.tcpServer.errorString(),
                    QMessageBox.Retry | QMessageBox.Cancel)
            if ret == QMessageBox.Cancel:
                return

        self.serverStatusLabel.setText("Listening")
        self.clientStatusLabel.setText("Connecting")

        self.tcpClient.connectToHost(QHostAddress(QHostAddress.LocalHost), self.tcpServer.serverPort())

    def acceptConnection(self):
        self.tcpServerConnection = self.tcpServer.nextPendingConnection()
        self.tcpServerConnection.readyRead.connect(self.updateServerProgress)
        self.tcpServerConnection.error.connect(self.displayError)

        self.serverStatusLabel.setText("Accepted connection")
        self.tcpServer.close()

    def startTransfer(self):
        self.bytesToWrite = Dialog.TotalBytes - self.tcpClient.write(QByteArray(Dialog.PayloadSize, '@'))
        self.clientStatusLabel.setText("Connected")

    def updateServerProgress(self):
        self.bytesReceived += self.tcpServerConnection.bytesAvailable()
        self.tcpServerConnection.readAll()

        self.serverProgressBar.setMaximum(Dialog.TotalBytes)
        self.serverProgressBar.setValue(self.bytesReceived)
        self.serverStatusLabel.setText("Received %dMB" % (self.bytesReceived / (1024 * 1024)))

        if self.bytesReceived == Dialog.TotalBytes:
            self.tcpServerConnection.close()
            self.startButton.setEnabled(True)
            QApplication.restoreOverrideCursor()

    def updateClientProgress(self, numBytes):
        self.bytesWritten += numBytes
        if self.bytesToWrite > 0:
            self.bytesToWrite -= self.tcpClient.write(QByteArray(
                                        min(self.bytesToWrite, Dialog.PayloadSize), '@'))

        self.clientProgressBar.setMaximum(Dialog.TotalBytes)
        self.clientProgressBar.setValue(self.bytesWritten)
        self.clientStatusLabel.setText("Sent %dMB" % (self.bytesWritten / (1024 * 1024)))

    def displayError(self, socketError):
        if socketError == QTcpSocket.RemoteHostClosedError:
            return

        QMessageBox.information(self, "Network error",
                "The following error occured: %s." % self.tcpClient.errorString())

        self.tcpClient.close()
        self.tcpServer.close()
        self.clientProgressBar.reset()
        self.serverProgressBar.reset()
        self.clientStatusLabel.setText("Client ready")
        self.serverStatusLabel.setText("Server ready")
        self.startButton.setEnabled(True)
        QApplication.restoreOverrideCursor()
Exemplo n.º 39
0
 def __init__(self):
     super(TcpServer, self).__init__()
     self.server = QTcpServer()
     self.server.newConnection.connect(self.incomingConnection)
Exemplo n.º 40
0
class Server(QDialog):
    FORTUNES = (
        "You've been leading a dog's life. Stay off the furniture.",
        "You've got to think about tomorrow.",
        "You will be surprised by a loud noise.",
        "You will feel hungry again in another hour.",
        "You might have mail.",
        "You cannot kill time without injuring eternity.",
        "Computers are not intelligent. They only think they are.")

    def __init__(self, parent=None):
        super(Server, self).__init__(parent)

        self.tcpServer = None
        self.networkSession = None

        self.statusLabel = QLabel()
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        manager = QNetworkConfigurationManager()
        if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired:
            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            id = settings.value('DefaultNetworkConfiguration', '')
            settings.endGroup()

            config = manager.configurationFromIdentifier(id)
            if config.state() & QNetworkConfiguration.Discovered == 0:
                config = manager.defaultConfiguration()

            self.networkSession = QNetworkSession(config, self)
            self.networkSession.opened.connect(self.sessionOpened)

            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
        else:
            self.sessionOpened()

        quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.sendFortune)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Server")

    def sessionOpened(self):
        if self.networkSession is not None:
            config = self.networkSession.configuration()

            if config.type() == QNetworkConfiguration.UserChoice:
                id = self.networkSession.sessionProperty('UserChoiceConfiguration')
            else:
                id = config.identifier()

            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            settings.setValue('DefaultNetworkConfiguration', id)
            settings.endGroup();

        self.tcpServer = QTcpServer(self)
        if not self.tcpServer.listen():
            QMessageBox.critical(self, "Fortune Server",
                    "Unable to start the server: %s." % self.tcpServer.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.statusLabel.setText("The server is running on\n\nIP: %s\nport %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.tcpServer.serverPort()))

    def sendFortune(self):
        fortune = self.FORTUNES[random.randint(0, len(self.FORTUNES) - 1)]

        block = QByteArray()
        out = QDataStream(block, QIODevice.WriteOnly)
        out.setVersion(QDataStream.Qt_4_0)
        out.writeUInt16(0)
        out.writeQString(fortune)
        out.device().seek(0)
        out.writeUInt16(block.size() - 2)

        clientConnection = self.tcpServer.nextPendingConnection()
        clientConnection.disconnected.connect(clientConnection.deleteLater)

        clientConnection.write(block)
        clientConnection.disconnectFromHost()
Exemplo n.º 41
0
class TestTransact(XWidget, Ui_Form):
    def __init__(self):
        super(TestTransact, self).__init__()
        self.setupUi(self)

        try:
            self._init_device_config()

            self._init_terminal_operation()
            self._init_online_parameters()
        except Exception as e:
            print("here exception")
            self.exception(e)

    # ********************************************** Init ****************************************************

    def _init_device_config(self):
        self.deviceconfig = DeviceConfig()
        self.deviceconfig.print_signal.connect(self.print_signal)
        self.layout_DeviceConfig.addWidget(self.deviceconfig)

    def _init_terminal_operation(self):
        self.port = 12345
        self.serveropened = False
        self._onPushButton_Openserver_Clicked()

    def _init_online_parameters(self):
        self.comboBox_AuthorizationResponseCode.addItems(['00:Approve', '51:Decline'])

        self._issuerdata = ['']
        try:
            with open('script/transact/issuerdata', 'r') as fd:
                for line in fd.readlines():
                    line = line.replace('\n', '').replace('\r', '')
                    self._issuerdata.append(line)
                fd.close()
        except Exception as e:
            self.exception(e)
        self.comboBox_IssuerAppData.addItems(self._issuerdata)

    def showEvent(self, QShowEvent):
        try:
            if self.config.get('comboBox_AuthorizationResponseCode'):
                self.comboBox_AuthorizationResponseCode.setCurrentText(self.config['comboBox_AuthorizationResponseCode'])
            if self.config.get('comboBox_IssuerAppData'):
                self.comboBox_IssuerAppData.setCurrentText(self.config['comboBox_IssuerAppData'])
        except Exception as e:
            self.exception(e)
        super().showEvent(QShowEvent)

    def hideEvent(self, QHideEvent):
        try:
            self.config['comboBox_AuthorizationResponseCode'] = self.comboBox_AuthorizationResponseCode.currentText()
            self.config['comboBox_IssuerAppData'] = self.comboBox_IssuerAppData.currentText()
        except Exception as e:
            self.exception(e)
        super().hideEvent(QHideEvent)

    # ********************************************** Slot ****************************************************

    def _onPushButton_Openserver_Clicked(self):
        print("start socker at ",self.port)

        if self.serveropened is False:
            #start init qtcpserver
            self.tcpServer = QTcpServer(self)
            address = QHostAddress('0.0.0.0')
            if not self.tcpServer.listen(address, self.port):
                print("cant listen!")
                self.close()
                return
            self.tcpServer.newConnection.connect(self.dealCommunication)
            self.fillActivateIps()

    def dealCommunication(self):
        # Get a QTcpSocket from the QTcpServer

        print("start handle")
        self.print_signal.emit("info", "connected")

        self.tcpSocket =  self.tcpServer.nextPendingConnection()
        #first read
        self.tcpSocket.readyRead.connect(self.showMessage)
        self.tcpSocket.disconnected.connect(self.showDisconnect)

    def showMessage(self):
        print ("start read show message")
        self.tcpSocket.readAll()

        #construct return data here
        origstr = self.comboBox_IssuerAppData.currentText()
        lenofstr = int(len(origstr) / 2)
        origstr2 = self.comboBox_AuthorizationResponseCode.currentText()
        finalstr = "8A02{:02}{:02}91{:02X}{}".format(int(origstr2[0]) + 30, int(origstr2[1])+30, lenofstr, origstr)
        print("return:", finalstr)

        self.tcpSocket.write(finalstr.encode("utf-8"))

    def showDisconnect(self):
        self.print_signal.emit("info", "disconnected")

    def fillActivateIps(self):
        print("start fill")
        for interface in QNetworkInterface.allInterfaces():
            iflags = interface.flags()
            if (iflags & QNetworkInterface.IsRunning) and  not (iflags  & QNetworkInterface.IsLoopBack) :
                for addrentry in interface.addressEntries():
#                    print("append ",addrentry.ip().toString(),addrentry.ip().protocol())
                    if addrentry.ip().protocol() == QAbstractSocket.IPv4Protocol:
                        self.plainTextEdit_iplist.appendPlainText("{}:{}".format(addrentry.ip().toString(), self.port))
Exemplo n.º 42
0
class CodeExecutor(object):
    """
    This class is responsible for executing code (when starting Tribler in debug mode).
    The protocol to execute code is as follows.
    First, a client that wants to execute some code opens a connection with the TCP server and sends the
    string: <code in base64 format> <task_id>\n
    This code will be executed and the result will be sent to the client in the following format:
    result <result> <task_id>\n.
    If Tribler crashes, the server sends the following result: crash <stack trace in base64 format>

    Note that the socket uses the newline as separator.
    """

    def __init__(self, port, shell_variables={}):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.tcp_server = QTcpServer()
        self.sockets = []
        self.stack_trace = None
        if not self.tcp_server.listen(port=port):
            self.logger.error("Unable to start code execution socket! Error: %s", self.tcp_server.errorString())
        else:
            self.tcp_server.newConnection.connect(self._on_new_connection)

        self.shell = Console(locals=shell_variables)

    def _on_new_connection(self):
        while self.tcp_server.hasPendingConnections():
            socket = self.tcp_server.nextPendingConnection()
            socket.readyRead.connect(self._on_socket_read_ready)
            socket.disconnected.connect(lambda dc_socket=socket: self._on_socket_disconnect(dc_socket))
            self.sockets.append(socket)

            # If Tribler has crashed, notify the other side immediately
            if self.stack_trace:
                self.on_crash(self.stack_trace)

    def run_code(self, code, task_id):
        self.shell.runcode(code)
        stdout = self.shell.stdout.read()
        stderr = self.shell.stderr.read()

        self.logger.info("Code execution with task %s finished:", task_id)
        self.logger.info("Stdout of task %s: %s", task_id, stdout)
        if 'Traceback' in stderr and 'SystemExit' not in stderr:
            self.logger.error("Executed code with failure: %s", b64encode(code))

        # Determine the return value
        if 'return_value' not in self.shell.console.locals:
            return_value = ''.encode('base64')
        else:
            return_value = str(self.shell.console.locals['return_value']).encode('base64')

        for socket in self.sockets:
            socket.write("result %s %s\n" % (return_value, task_id))

    def on_crash(self, exception_text):
        self.stack_trace = exception_text
        for socket in self.sockets:
            socket.write("crash %s\n" % exception_text.encode('base64'))

    def _on_socket_read_ready(self):
        data = str(self.sockets[0].readAll())
        parts = data.split(" ")
        if len(parts) != 2:
            return

        try:
            code = parts[0].decode('base64')
            task_id = parts[1].replace('\n', '')
            self.run_code(code, task_id)
        except binascii.Error:
            self.logger.error("Invalid base64 code string received!")

    def _on_socket_disconnect(self, socket):
        self.sockets.remove(socket)
Exemplo n.º 43
0
def isAvailable(port):
    server = QTcpServer()
    result = server.listen(QHostAddress("127.0.0.1"), port)
    server.close()
    return result