Exemple #1
0
    def __init__(self, parent=None):
        super(ServerDlg, self).__init__("&Close Server", parent)
        self.setWindowFlags(QC.Qt.WindowStaysOnTopHint)

        self.tcpServer = QN.QTcpServer(self)

        #Zjistím si svojí IP adresu
        for address in QN.QNetworkInterface.allAddresses():
            if address != QN.QHostAddress.LocalHost and address.toIPv4Address(
            ):
                break
        else:
            address = QN.QHostAddress.LocalHost

        #print(address.toString())

        self.tcpServer.listen(QN.QHostAddress("0.0.0.0"), PORT)  #Any address
        self.tcpServer.newConnection.connect(self.addConnection)
        self.connections = [None for _ in range(6)]
        self.connectionAddress = [None for _ in range(6)]
        self.players = {}

        self.clicked.connect(self.close)
        font = self.font()
        font.setPointSize(24)
        self.setFont(font)
        self.setWindowTitle("Server")
    def __init__(self):
        """Initialize"""
        super().__init__()
        self.server = qtn.QTcpServer()
        self.sock = qtn.QTcpSocket(self.server)
        # if self.server.listen(qtn.QHostAddress(self.ip), self.s):
        if self.server.listen(qtn.QHostAddress.LocalHost, self.s):
            print(
                f'DATA SERVER:\n\tAddress: {self.server.serverAddress().toString()}\n\tPort: {str(self.server.serverPort())}'
            )
        else:
            print('ERROR!!!!')
            exit()
        self.server.newConnection.connect(self.__session)

        f = open('key.bin', 'rb')

        self.key = f.read()

        f.close()

        self.f = Fernet(self.key)

        del self.key

        # set your properties
        self.db = mysql.connector.connect(host='localhost',
                                          user='******',
                                          passwd='password',
                                          database='login_data',
                                          auth_plugin='mysql_native_password')

        self.mycursor = self.db.cursor()
Exemple #3
0
def test_addConnection_2():
    app.tcpServer = QtNetwork.QTcpServer(app)
    with mock.patch.object(app.tcpServer,
                           'nextPendingConnection',
                           return_value=0):
        suc = app.addConnection()
        assert not suc
    def connect_server(self):
        # Get the saved data from the settings file
        self.host = self.cfg_data.get_rpi_host()  # Get the TCP connection host
        self.port = self.cfg_data.get_rpi_port()  # Get the TCP connection port
        rem_stat = self.cfg_data.get_server_remote("TCPRPiServ")

        if rem_stat == "no":
            self.host = QtNetwork.QHostAddress.LocalHost
        elif rem_stat == "yes":
            for ip_address in QtNetwork.QNetworkInterface.allAddresses():
                if ip_address != QtNetwork.QHostAddress.LocalHost and ip_address.toIPv4Address(
                ) != 0:
                    break  # If we found an IP then we exit the loop
                else:
                    ip_address = QtNetwork.QHostAddress.LocalHost  # If no IP is found, assign localhost
            self.host = ip_address  # Assign the IP address that wa found above
        # TODO Add the ability to incorporate custom IP addresses

        self.tcp_server = QtNetwork.QTcpServer()  # Create a server object
        self.tcp_server.newConnection.connect(
            self._new_connection)  # Handler for a new connection

        self.tcp_server.listen(self.host, int(
            self.port))  # Start listening for connections
        self.conStatSigR.emit(
            "Waiting")  # Indicate that the server is listening on the GUI
        self.logger.debug("RPI server connection initializer called")
Exemple #5
0
def test_startCommunication_3():
    app.tcpServer = None
    server = QtNetwork.QTcpServer(app)
    hostAddress = QtNetwork.QHostAddress('127.0.0.1')
    server.listen(hostAddress, 3490)
    suc = app.startCommunication()
    assert not suc
Exemple #6
0
 def run(self):
     '''This starts the thread running, but it must not be called directly,
        it must be started with Server.start() instead for it to be started
        in its own thread. If it is called directly then it will run in 
        the thread in which it was called.'''
     self.debug = False
     self.lock = False
     for i in QtNetwork.QNetworkInterface.allAddresses():
         print("Found Address:", i.toString())
         if i != QtNetwork.QHostAddress.LocalHost and i.protocol() == QtNetwork.QAbstractSocket.IPv4Protocol:
             self.address = i
             break
     # This determines the IP adress of the server
     self.tcpServer = QtNetwork.QTcpServer(self)
     self.tcpServer.listen(QtNetwork.QHostAddress("0.0.0.0"), self.port)
     # Listen on all addreses on the specified port only
     self.tcpServer.newConnection.connect(self.addConnection)
     # Call self.addConnection whenever the server signals that there is a new inbound connection
     print("Server Initialised")
     self.constantTimer = QtCore.QTimer()
     self.constantTimer.timeout.connect(self.checkQueue)
     self.constantTimer.start(1)
     print("Server Checking Queue")
     # Integrate the checkQueue function into the QT event loop, with
     # a delay between calls of 1 millisecond
     self.receiveQueue.put({"action":"showAddress", "port":self.port, "address":self.address, "client":"thread"})
Exemple #7
0
    def __init__(self, scene_server_port):

        super(RescuersGui, self).__init__()

        self.port = scene_server_port
        self.rpm = rospy.get_param("/art/interface/projected_gui/rpm")
        self.xinput = "USBest Technology SiS HID Touch Controller"

        self.tcpServer = QtNetwork.QTcpServer(self)
        if not self.tcpServer.listen(port=self.port):
            rospy.logerr(
                'Failed to start scene TCP server on port ' + str(self.port))

        self.tcpServer.newConnection.connect(self.new_connection)
        self.connections = []

        self.scene_timer = QtCore.QTimer()
        self.scene_timer.timeout.connect(self.send_to_clients_evt)
        self.scene_timer.start(1.0 / 15 * 1000)

        self.projectors = [ProjectorCalibrator("localhost")]

        rospy.loginfo("Waiting for projector nodes...")
        for proj in self.projectors:
            proj.wait_until_available()
            if not proj.is_calibrated():
                rospy.loginfo("Starting calibration of projector: " + proj.proj_id)
                proj.calib_pub.publish(False)
                proj.calibrate(self.calibrated_cb)
            else:
                rospy.loginfo("Projector " + proj.proj_id + " already calibrated.")
                proj.calib_pub.publish(True)
Exemple #8
0
def pick_free_port():
    """ Picks a free port """
    srv = QtNetwork.QTcpServer()
    srv.listen()
    port = srv.serverPort()
    srv.close()
    del srv
    return port
 def serverIni(self):
     self.outLog('server initialize')
     self.serverSocket = QtNetwork.QTcpServer()
     if self.serverSocket.listen(QtNetwork.QHostAddress.Any,
                                 self.params['server']['port']):
         self.serverSocket.newConnection.connect(self.newConnection)
     else:
         exit(0)
     pass
Exemple #10
0
 def init_tcp(self, is_server, addr):
     if is_server:
         self.server = QtNetwork.QTcpServer(self)
         self.server.listen(QtNetwork.QHostAddress.Any, 8888)
         self.server.newConnection.connect(self.start_new_connection)
     else:
         self.socket = QtNetwork.QTcpSocket(self)
         self.socket.connectToHost(QtNetwork.QHostAddress(addr), 8888)
         self.socket.readyRead.connect(self.recv)
Exemple #11
0
 def autoDetectNetworkInterface(self):
     hostAddresses = []
     interfaceFlags = QtNetwork.QNetworkInterface.IsUp | \
                       QtNetwork.QNetworkInterface.IsRunning
     # Grab all available interfaces
     allInterfaces = QtNetwork.QNetworkInterface.allInterfaces()
     for interface in allInterfaces:
         if ((interface.flags() & interfaceFlags == interfaceFlags) \
             ):#and (interface.flags() &
             #           QtNetwork.QNetworkInterface.IsLoopBack == 0)):
             addresses = interface.addressEntries()
             for address in addresses:
                 if (address.ip().protocol() ==
                         QtNetwork.QAbstractSocket.IPv4Protocol) and \
                                 address.ip() != (
                                 QtNetwork.QHostAddress(
                                     QtNetwork.QHostAddress.LocalHost)):
                     hostAddresses.append(address.ip())
                     # If there is more than one host address detected,
                     # show error dialog
                     if len(hostAddresses) > 1:
                         alert = AlertDialog(
                             "Network Error",
                             "Could not auto detect network "
                             "settings")
                         alert.show()
                     else:  # only one IP address returned, try port 80
                         testServer = QtNetwork.QTcpServer(self)
                         # Try to start a QTcpServer at hostAddress:80
                         # If the server starts, return those values as
                         # detected values
                         if testServer.listen(hostAddresses[0], 80):
                             ipAddress = hostAddresses[0].toString()
                             # populate server text boxes
                             self.hostAddressTextBox.setText(ipAddress)
                             self.hostPortTextBox.setText(str(80))
                             testServer.close()
                         else:
                             # Could not listen at detected IP address and
                             # port 80. This may be because port 80 is
                             # being used by another service, so let
                             # QTcpServer pick the port.
                             if testServer.listen(hostAddresses[0]):
                                 ipAddress = hostAddresses[0].toString()
                                 port = testServer.serverPort()
                                 # populate server text boxes
                                 self.hostAddressTextBox.setText(ipAddress)
                                 self.hostPortTextBox.setText(str(port))
                                 testServer.close()
                             else:  # Can't auto detect network settings
                                 alert = AlertDialog(
                                     "Network Error", "Could not auto "
                                     "detect  network "
                                     "settings")
                                 alert.show()
Exemple #12
0
 def startNotifier(self):
     if self.protocol() == 'unix':
         address = tempfile.mktemp(prefix="pmx")
         self.notifier = QtNetwork.QLocalServer(self)
         self.notifier.listen(address)
     else:
         self.notifier = QtNetwork.QTcpServer(self)
         self.notifier.listen()
         address = "%s:%d" % (self.notifier.serverAddress().toString(),
                              self.notifier.serverPort())
     self.notifier.newConnection.connect(self.on_notifier_newConnection)
     return address
Exemple #13
0
    def on_btnOpen_clicked(self):
        self.server = QtNetwork.QTcpServer()
        self.server.listen(QtNetwork.QHostAddress("0.0.0.0"), PORT)
        self.server.setObjectName("server")
        self.server.newConnection.connect(self.on_server_newConnection)

        self.totalsize = 0
        self.bytereceived = 0
        self.filename = ""
        self.inblock = QByteArray()

        self.on_bwr_update("open server begin receiving")
	def __init__( self, parent, identifier_string, listener_address, port, timeout_ms=5000 ):
		super().__init__( parent )
		#self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.timeout_ms = timeout_ms
		self.port_for_ping = int(port)
		self.active_connections = {}
		self.tcp_server = QtNetwork.QTcpServer()
		self.udp_socket = QtNetwork.QUdpSocket()
		self.identifier_string = identifier_string
		if not listener_address or listener_address == '':
			listener_address = QtNetwork.QHostAddress.AnyIPv4
		if( not self.Listen_For_Replies( listener_address ) ):
			raise Exception( "Failed to find local network " + listener_address.toString() )
    def __init__(self, username, recipient):
        super().__init__()
        self.username = username
        self.recipient = recipient

        self.listener = qtn.QTcpServer()
        self.listener.listen(qtn.QHostAddress.Any, self.port)
        self.listener.acceptError.connect(self.on_error)
        self.listener.newConnection.connect(self.on_connection)
        self.connections = []

        self.client_socket = qtn.QTcpSocket()
        self.client_socket.error.connect(self.on_error)
Exemple #16
0
    def __init__(self, logger):
        super(SocketListener, self).__init__()
        self.logger = logger

        self.udpSocket = QtNetwork.QUdpSocket(self)
        self.udpSocket.bind(QtNetwork.QHostAddress.Any, 11211)
        self.udpSocket.readyRead.connect(self.readUdpSocket)

        self.tcpServer = QtNetwork.QTcpServer(self)
        self.tcpServer.listen(QtNetwork.QHostAddress.Any, 11211)
        self.tcpServer.newConnection.connect(self.tcpConnection)

        self.tcpConnection = None
        self.tcpData = b''
	def __init__( self, parent, identifier_string, listener_address, port, timeout_ms=20000 ):
		super().__init__( parent )
		#self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
		self.timeout_ms = timeout_ms
		self.port_for_ping = int(port)
		self.active_connections = {}
		self.tcp_server = QtNetwork.QTcpServer()
		self.udp_socket = QtNetwork.QUdpSocket()
		self.identifier_string = identifier_string
		if( not self.Listen_For_Replies( listener_address ) ):
			if listener_address is None:
				raise Exception( "Failed to listen on default ip" )
			else:
				raise Exception( "Failed to listen on ip " + listener_address.toString() )
Exemple #18
0
    def __init__(self, parent: QtCore.QObject = None):
        # Super call
        super(HTTP, self).__init__(parent=parent)

        # Internal attributes
        self._socket: QtNetwork.QTcpServer = QtNetwork.QTcpServer(parent=self)
        self._client: typing.Optional[QtNetwork.QTcpSocket] = None

        # Aliases
        qt_disconnect = super(HTTP, self).disconnect
        qt_connect = super(HTTP, self).connect

        # Internal calls
        self._socket.newConnection.connect(self.process_new_client)
        self._socket.acceptError.connect(self.process_connection_error)
        self._socket.setMaxPendingConnections(2)
Exemple #19
0
 def __init__(self, parent=None):
     super(ServerManager, self).__init__(parent)
     self._server = QtNetwork.QTcpServer(self)
     self._server.newConnection.connect(self.on_newConnection)
     self._clients = {}
     self._keyboards = {
         "454545": QtNetwork.QTcpSocket,
         "123123": QtNetwork.QTcpSocket
     }
     self._displays = {"456456": QtNetwork.QTcpSocket}
     self._distributors = {}
     self._counters = {"122": {"count": 5}, "123": {"count": 10}}
     self._client_type = {
         "0": "Keyboard",
         "1": "display",
         "2": "distributor"
     }
Exemple #20
0
def test_addConnection_3():
    class Test(QObject):
        nextBlockSize = 0
        readyRead = pyqtSignal()
        disconnected = pyqtSignal()
        error = pyqtSignal()

        @staticmethod
        def peerAddress():
            return Test()

        @staticmethod
        def toString():
            return 'Test'
    app.tcpServer = QtNetwork.QTcpServer(app)
    with mock.patch.object(app.tcpServer,
                           'nextPendingConnection',
                           return_value=Test()):
        suc = app.addConnection()
        assert suc
    def connect_stellarium(self):
        # Get the saved data from the settings file
        self.host = self.cfg_data.get_stell_host()  # Get the TCP connection host
        self.port = self.cfg_data.get_stell_port()  # Get the TCP connection port

        if self.host == "localhost" or self.host == "127.0.0.1":
            self.host = QtNetwork.QHostAddress.LocalHost
        else:
            for ip_address in QtNetwork.QNetworkInterface.allAddresses():
                if ip_address != QtNetwork.QHostAddress.LocalHost and ip_address.toIPv4Address() != 0:
                    break
                else:
                    ip_address = QtNetwork.QHostAddress.LocalHost
            self.host = ip_address

        self.tcp_server = QtNetwork.QTcpServer()  # Create a server object
        self.tcp_server.newConnection.connect(self._new_connection)  # Handler for a new connection

        self.tcp_server.listen(self.host, int(self.port))  # Start listening for connections
        self.conStatSigS.emit("Waiting")  # Indicate that the server is listening on the GUI
        self.logger.debug("Stellarium server connection initializer called")
Exemple #22
0
    def startCommunication(self):
        """
        startCommunication prepares the remote listening by starting a tcp server listening
        on localhost and port 3490.

        :return: success
        """

        if self.tcpServer is not None:
            return False

        self.tcpServer = QtNetwork.QTcpServer(self)
        hostAddress = QtNetwork.QHostAddress('127.0.0.1')

        if not self.tcpServer.listen(hostAddress, 3490):
            self.log.warning('Port already in use')
            self.tcpServer = None
            return False
        else:
            self.log.info('Remote access enabled')
            self.tcpServer.newConnection.connect(self.addConnection)
            return True
Exemple #23
0
    def __init__(self, x, y, width, height, rpm, scene_server_port):

        super(RescuersGui, self).__init__()

        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.rpm = rpm
        self.port = scene_server_port

        self.tcpServer = QtNetwork.QTcpServer(self)
        if not self.tcpServer.listen(port=self.port):
            rospy.logerr('Failed to start scene TCP server on port ' +
                         str(self.port))

        self.tcpServer.newConnection.connect(self.new_connection)
        self.connections = []

        self.scene_timer = QtCore.QTimer()
        self.scene_timer.timeout.connect(self.send_to_clients_evt)
        self.scene_timer.start(1.0 / 15 * 1000)

        self.projectors = [ProjectorHelper("localhost")]

        rospy.loginfo("Waiting for projector nodes...")
        for proj in self.projectors:
            proj.wait_until_available()
            if not proj.is_calibrated():
                rospy.loginfo("Starting calibration of projector: " +
                              proj.proj_id)
                proj.calibrate(self.calibrated_cb)
            else:
                rospy.loginfo("Projector " + proj.proj_id +
                              " already calibrated.")

        rospy.loginfo("Ready")
    def connect_server(self):
        """
        Whenever we want a new TCP connection this function is called.
        :return: Nothing
        """
        if self.host == "localhost":
            self.host = QtNetwork.QHostAddress.LocalHost
        else:
            for ip_address in QtNetwork.QNetworkInterface.allAddresses():
                if ip_address != QtNetwork.QHostAddress.LocalHost and ip_address.toIPv4Address(
                ) != 0:
                    break
                else:
                    ip_address = QtNetwork.QHostAddress.LocalHost
            self.host = ip_address  # Save the local IP address

        self.tcp_server = QtNetwork.QTcpServer()  # Create a server object
        self.tcp_server.newConnection.connect(
            self._new_connection)  # Handler for a new connection
        self.sendDataClient.connect(
            self.send)  # Connect the signal trigger for data sending

        self.tcp_server.listen(QtNetwork.QHostAddress(self.host), int(
            self.port))  # Start listening for connections
Exemple #25
0
    def __init__(self, parent=None):
        super(WebServer, self).__init__(parent)

        self.HTTPMethods = {'GET': self._processGET}
        self.webResources = {}
        self.tcpServer = QtNetwork.QTcpServer(self)
Exemple #26
0
    def __init__(self, portNumber):
        super(TcpServer, self).__init__(None)

        self.portNumber = portNumber
        self.tcpServer = QtNetwork.QTcpServer()
        self.tcpServer.newConnection.connect(self.onNewTcpConnection)
Exemple #27
0
def test_stopCommunication_2():
    app.clientConnection = QtNetwork.QTcpServer(app)
    suc = app.stopCommunication()
    assert suc
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

'''
    Basic actions of QTcpServer, QTcpSocket communication.
'''

from PyQt5 import QtCore, QtNetwork

def new_server_connection():
    print('new server connection')

def new_client_connection():
    print('new client connection')

def setup():
    server.listen(QtNetwork.QHostAddress.LocalHost, 34543)
    client_socket.connectToHost(QtNetwork.QHostAddress.LocalHost, 34543)


app = QtCore.QCoreApplication([])

server = QtNetwork.QTcpServer()
server.newConnection.connect(new_server_connection)
client_socket = QtNetwork.QTcpSocket()
client_socket.connected.connect(new_client_connection)

QtCore.QTimer.singleShot(0, setup)
QtCore.QTimer.singleShot(3000, app.quit)
app.exec_()
 def __init__(self):
     super().__init__()
     self.tcp_server = QtNetwork.QTcpServer(self)
     self.tcp_server.acceptError.connect(self.accept_error)
     self.tcp_server.newConnection.connect(self._new_connection)