Esempio n. 1
0
 def comboboxInit(self):
     # 工具选择框combox
     self.widgetui.comboBoxStyle.insertItem(0, "UDP")
     self.widgetui.comboBoxStyle.insertItem(1, "TCP Client")
     self.widgetui.comboBoxStyle.insertItem(2, "TCP Server")
     self.widgetui.comboBoxStyle.insertItem(3, "COM Tool")
     self.connectModeList = list()
     self.connectModeList.append('UDP')
     self.connectModeList.append('TCP Client')
     self.connectModeList.append('TCP Server')
     self.connectModeList.append('COM Tool')
     self.widgetui.comboBoxStyle.activated.connect(self.comboxClicked)
     # 波特率combox
     self.widgetui.comboBoxBaud.insertItems(0, baudList)
     self.widgetui.comboBoxBaud.setCurrentText("9600")
     self.widgetui.comboBoxBaud.hide()
     self.widgetui.comboComNum.hide()
     self.widgetui.comboBoxClientList.hide()  # tcp的server专用的组合框
     # 本地IP combobox
     self.myhostInfo = QHostInfo.fromName(QHostInfo.localHostName())
     hostIpList = ICommunicateTCPIP.getLocalIpList()
     if '127.0.0.1' not in hostIpList:
         hostIpList.append('127.0.0.1')
     oldHostIp = str(self.myconfig.getValue("hostIp"))
     tempHostIp = str()
     for ip in hostIpList:
         self.widgetui.comboBoxLocal.addItem(ip)
         if oldHostIp == ip:
             tempHostIp = ip
     self.widgetui.comboBoxLocal.setCurrentText(tempHostIp)
     self.myaddress = self.widgetui.comboBoxLocal.currentText()
    def run(self):
        localHostName = QHostInfo.localHostName()
        hostinfo = QHostInfo.fromName(localHostName)
        listaddress = hostinfo.addresses()

        for address in listaddress:
            if QHostAddress(
                    address).protocol() == QAbstractSocket.IPv4Protocol:
                address = QHostAddress(address).toString()
        print(address)

        host_info = ""
        confList = QNetworkConfigurationManager().allConfigurations()
        print("confList = ", confList.__len__())
        for conf in confList:
            if str(conf.bearerTypeName()) == "Ethernet":
                host_info += "\n"
                host_info += "name : " + QNetworkConfiguration(
                    conf).name() + "\n"
                host_info += str(QNetworkConfiguration(conf).isValid()) + "\n"
                host_info += "bearerType: " + QNetworkConfiguration(
                    conf).bearerTypeName() + "\n"

        list = QNetworkInterface.allInterfaces()
        for interface in list:
            host_info += "\n"
            host_info += "=============================\n"
            host_info += "name: " + interface.name() + "\n"
            host_info += QNetworkInterface(interface).hardwareAddress() + "\n"
            host_info += str(QNetworkInterface(interface).isValid()) + "\n"
            host_info += "---------\n"
            if QNetworkInterface(interface).flags() & QNetworkInterface.IsUp:
                host_info += "Interface: is up\n"
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsLoopBack:
                host_info += "Interface: is loop back\n"  # 迴環地址
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsRunning:
                host_info += "Interface: is running \n"  # 網絡已經啓動運行
            if interface.flags() & QNetworkInterface.CanMulticast:
                host_info += "Interface: CanMulticast\n"  # 多播
            if interface.flags() & QNetworkInterface.CanBroadcast:
                host_info += "Interface: CanBroadcast\n"
            host_info += "---------\n"

            entryList = QNetworkInterface(interface).addressEntries()
            for entry in entryList:
                address = entry.ip()
                if QHostAddress(address).protocol(
                ) == QAbstractSocket.IPv4Protocol:  # and  \
                    # str(address.toString()) != "127.0.0.1":
                    host_info += "IP Address: " + QNetworkAddressEntry(
                        entry).ip().toString() + "\n"
                    host_info += "Netmask: " + QNetworkAddressEntry(
                        entry).netmask().toString() + "\n"
                    host_info += "Broadcast: " + QNetworkAddressEntry(
                        entry).broadcast().toString() + "\n"
            host_info += "=============================\n"
        self.sig.emit(host_info)
Esempio n. 3
0
    def run(self):
        #       获取IP
        socket = MyTcpsocket()
        socket.sign_recv.connect(self.sign_thread_recv)
        self.sign_thread_send.connect(socket.sign_send)

        hostname = QHostInfo.localHostName()
        info = QHostInfo.fromName(hostname)
        self.sign_thread_start.emit(info.addresses()[0].toString())
        self.exec_()
Esempio n. 4
0
 def getLocalIpList():
     """
     返回本地网卡的ip列表
     :return: strlist
     """
     myHostInfo = QHostInfo.fromName(QHostInfo.localHostName())
     ipv4_addrs = list(
         filter(
             lambda myaddr: myaddr.protocol() == QAbstractSocket.
             IPv4Protocol, myHostInfo.addresses()))
     ipv4_straddrs = list(map(lambda myaddr: myaddr.toString(), ipv4_addrs))
     return ipv4_straddrs
Esempio n. 5
0
 def __init__(self, port, data_cb):
     QUdpSocket.__init__(self)
     self._session = QTurnSession(self)
     self._state = TURNState.UNBOUND
     self.bindings = {}
     self.initial_port = port
     self._data_cb = data_cb
     self.turn_host, self.turn_port = config.Settings.get('turn/host', type=str, default='dev.faforever.com'), \
                            config.Settings.get('turn/port', type=int, default=3478)
     self._logger.info("Turn socket initialized: {}".format(self.turn_host))
     self.turn_address = None
     QHostInfo.lookupHost(self.turn_host, self._looked_up)
     self.bind(port)
     self.readyRead.connect(self._readyRead)
     self.error.connect(self._error)
Esempio n. 6
0
def _is_url_dns(urlstr):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as a string.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    url = qurl_from_user_input(urlstr)
    assert url.isValid()

    if (utils.raises(ValueError, ipaddress.ip_address, urlstr) and
            not QHostAddress(urlstr).isNull()):
        log.url.debug("Bogus IP URL -> False")
        # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs
        # which we don't want to.
        return False

    host = url.host()
    if not host:
        log.url.debug("URL has no host -> False")
        return False
    log.url.debug("Doing DNS request for {}".format(host))
    info = QHostInfo.fromName(host)
    return not info.error()
Esempio n. 7
0
def _is_url_dns(urlstr):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as a string.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    url = qurl_from_user_input(urlstr)
    assert url.isValid()

    if (utils.raises(ValueError, ipaddress.ip_address, urlstr)
            and not QHostAddress(urlstr).isNull()):
        log.url.debug("Bogus IP URL -> False")
        # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs
        # which we don't want to.
        return False

    host = url.host()
    if not host:
        log.url.debug("URL has no host -> False")
        return False
    log.url.debug("Doing DNS request for {}".format(host))
    info = QHostInfo.fromName(host)
    return not info.error()
Esempio n. 8
0
 def nickName(self):
     """
     Public method to get the nick name.
     
     @return nick name (string)
     """
     return "{0}@{1}@{2}".format(self.__username, QHostInfo.localHostName(),
                                 self.__servers[0].serverPort())
Esempio n. 9
0
 def host_to_addr(host: str) -> QHostAddress:
     """Get the IPv4 address of a given hostname.
     It is required to use this method in order to get the actual IP
     as it turns out that QHostAddress(host) does not do any DNS lookup.
     """
     host_info = QHostInfo.fromName(host)
     for address in host_info.addresses():
         if address.protocol() == QAbstractSocket.IPv4Protocol:
             return address
Esempio n. 10
0
 def nickName(self):
     """
     Public method to get the nick name.
     
     @return nick name (string)
     """
     return "{0}@{1}@{2}".format(
         self.__username,
         QHostInfo.localHostName(),
         self.__servers[0].serverPort()
     )
Esempio n. 11
0
    def listen_host_info(self):
        if not self.listening:
            return None

        s = self._server
        hi = '%s port %d' % (s.serverAddress().toString(), s.serverPort())
        from PyQt5.QtNetwork import QHostInfo
        host = QHostInfo.localHostName()
        if host:
            hi = '%s or %s' % (host, hi)
        return hi
Esempio n. 12
0
    def dnsResolve(self, host):
        """Resolve a DNS hostname.

        Resolves the given DNS hostname into an IP address, and returns it
        in the dot-separated format as a string.

        Args:
            host: hostname to resolve.
        """
        ips = QHostInfo.fromName(host)
        if ips.error() != QHostInfo.NoError or not ips.addresses():
            err_f = "Failed to resolve host during PAC evaluation: {}"
            log.network.info(err_f.format(host))
            return QJSValue(QJSValue.NullValue)
        else:
            return ips.addresses()[0].toString()
Esempio n. 13
0
    def dnsResolve(self, host):
        """Resolve a DNS hostname.

        Resolves the given DNS hostname into an IP address, and returns it
        in the dot-separated format as a string.

        Args:
            host: hostname to resolve.
        """
        ips = QHostInfo.fromName(host)
        if ips.error() != QHostInfo.NoError or not ips.addresses():
            err_f = "Failed to resolve host during PAC evaluation: {}"
            log.network.info(err_f.format(host))
            return QJSValue(QJSValue.NullValue)
        else:
            return ips.addresses()[0].toString()
Esempio n. 14
0
def _is_url_dns(url):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as QUrl, ideally via qurl_from_user_input.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    if not url.isValid():
        return False
    host = url.host()
    log.url.debug("DNS request for {}".format(host))
    if not host:
        return False
    info = QHostInfo.fromName(host)
    return not info.error()
Esempio n. 15
0
def _is_url_dns(url):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as QUrl, ideally via qurl_from_user_input.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    if not url.isValid():
        return False
    host = url.host()
    log.url.debug("DNS request for {}".format(host))
    if not host:
        return False
    info = QHostInfo.fromName(host)
    return not info.error()
Esempio n. 16
0
    def sendMessage(self, messageType, serverAddress=""):
        """
        发送消息,serverAddress是服务器IP地址
        """
        localHostName = QHostInfo.localHostName()
        ipAddress = self.getIP()

        username = self.getUserName()
        data = {
            "messageType": messageType,
            "userName": username,
            "localHostName": localHostName
        }

        if messageType == Chat.Message:
            if self.messageTextEdit.toPlainText() == "":
                QMessageBox.warning(self, "警告", "发送内容不能为空", QMessageBox.Ok)
                return

            message = self.getMessage()
            data["ipAddress"] = ipAddress
            data["message"] = message

        elif messageType in (Chat.NewParticipant, Chat.ParticipantLeft):
            data["ipAddress"] = ipAddress

        elif messageType == Chat.FileName:
            row = self.userTableWidget.currentRow()
            clientAddress = self.userTableWidget.item(row, 2).text()
            data["ipAddress"] = ipAddress
            data["clientAddress"] = clientAddress
            data["sendFileName"] = self.fileName
            # 取得文件接收方的IP地址(clientAddress),然后将本机地址(服务器地址)、文件接收方(客户端地址)、发送的文件名
            # 通过UDP协议广播出去。

        elif messageType == Chat.Refuse:
            data["ipAddress"] = serverAddress
            # 消息类型是Chat.Refuse时,我们会把服务器端的地址带入

        jdata = json.dumps(data)
        encodeData = bytes(jdata, encoding="utf-8")

        self.udpSocket.writeDatagram(encodeData, QHostAddress.Broadcast,
                                     self.port)
Esempio n. 17
0
 def onTimer(self):
     print("Timer")
     hostname = QHostInfo.localHostName()
     self.hostname_label.setText("ssh <username>@" + hostname + ".local.")
     if checkIfProcessRunning("sshd") == True:
         self.ssh_cb.setChecked(True)
         self.hostname_infolabel.setVisible(True)
         self.hostname_label.setVisible(True)
         self.vnc_cb.setEnabled(True)
     else:
         self.ssh_cb.setChecked(False)
         self.hostname_infolabel.setVisible(False)
         self.hostname_label.setVisible(False)
         self.vnc_infolabel.setVisible(False)
         self.vnc_cb.setEnabled(False)
     if checkIfProcessRunning("x11vnc") and checkIfProcessRunning("sshd") == True:
         self.vnc_cb.setChecked(True)
         self.vnc_infolabel.setVisible(True)
     else:
         self.vnc_cb.setChecked(False)
         self.vnc_infolabel.setVisible(False)
Esempio n. 18
0
    def sendMessage(self, messageType):
        """
        发送消息
        """
        localHostName = QHostInfo.localHostName()
        # 获得主机名

        ipAddress = self.getIP()

        username = self.getUserName()

        data = {
            "messageType": messageType,
            "userName": username,
            "localHostName": localHostName
        }
        # 我们构建一个消息数据,这个数据的类型,我们定义为字典,里面放了消息类型、用户名、主机名。

        if messageType == Chat.Message:
            if self.messageTextEdit.toPlainText() == "":
                QMessageBox.warning(self, "警告", "发送内容不能为空", QMessageBox.Ok)
                return

            message = self.getMessage()
            data["ipAddress"] = ipAddress
            data["message"] = message
            # 如果不是空消息,我们取得聊天框中的内容以及本地IP地址,并增加到消息数据当中。

        elif messageType in (Chat.NewParticipant, Chat.ParticipantLeft):
            data["ipAddress"] = ipAddress
        # 要是我们发送的消息类型是:Chat.NewParticipant和Chat.ParticipantLeft(新人报到、用户离开),我们取得Ip地址后并增加到消息数据中

        jdata = json.dumps(data)
        encodeData = bytes(jdata, encoding="utf-8")
        # 将消息data转成json格式,并通过bytes函数将其转成字节型的

        self.udpSocket.writeDatagram(encodeData, QHostAddress.Broadcast,
                                     self.port)
Esempio n. 19
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ''

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != '':
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != '':
                self.hostCombo.addItem(name + '.' + domain)

        if name != 'localhost':
            self.hostCombo.addItem('localhost')

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel("This examples requires that you run "
                                  "the Fortune Server example as well.")

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

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

        self.tcpSocket = QTcpSocket(self)

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.tcpSocket.readyRead.connect(self.readFortune)
        self.tcpSocket.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.portLineEdit.setFocus()

        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.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
Esempio n. 20
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ''
        self.title = "扫码收货PC辅助程序"

        hostLabel = QLabel('IP:')
        hostLabel.setFont(qtawesome.font('fa', 14))

        portLabel = QLabel('端口:')
        portLabel.setFont(qtawesome.font('fa', 14))

        taskCodeLabel = QLabel('任务码:')
        taskCodeLabel.setFont(qtawesome.font('fa', 14))
        self.serverMsgLable = QLabel('来自服务端的消息:')
        self.serverMsgLable.setFont(qtawesome.font('fa', 14))

        self.sendMsgLabel = QLabel('将要发送的消息:')
        self.sendMsgLabel.setFont(qtawesome.font('fa', 14))

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != '':
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != '':
                self.hostCombo.addItem(name + '.' + domain)

        if name != 'localhost':
            self.hostCombo.addItem('10.286.88.124')

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))
        self.portLineEdit.setPlaceholderText("请输入端口")

        self.taskLineEdit = QLineEdit()
        self.taskLineEdit.setPlaceholderText("请向组长询问后输入任务码")
        self.taskLineEdit.setValidator(QIntValidator(1, 9999, self))

        self.serverLineEdit = QLineEdit()
        self.serverLineEdit.setPlaceholderText('服务器发送的消息会显示在这里')

        self.sendTextEdit = QTextEdit()
        self.sendTextEdit.setPlaceholderText('请输入先要发送给服务器的消息')

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)
        taskCodeLabel.setBuddy(self.taskLineEdit)
        self.serverMsgLable.setBuddy(self.serverLineEdit)
        self.sendMsgLabel.setBuddy(self.sendTextEdit)

        self.statusLabel = QLabel("状态:尚未连接")
        self.statusLabel.setAutoFillBackground(True)
        self.statusLabel.setAlignment(Qt.AlignCenter)
        palette = QPalette()  # 新建一个调色板
        palette.setColor(QPalette.Window, Qt.red)  # 设置颜色
        self.statusLabel.setPalette(palette)
        self.statusLabel.setStyleSheet('''
                color:#ffffff;
                font-size:18px;
                font-weight:bold;
        ''')

        self.getFortuneButton = QPushButton("启动连接")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("退出")
        self.stopButton = QPushButton("中止连接")
        self.stopButton.setDefault(True)
        self.stopButton.setEnabled(False)

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.AcceptRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)
        self.sendMsgbutton = QPushButton('发送消息')
        self.webSocket = QWebSocket()

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.taskLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.CreateNewConn)
        self.stopButton.clicked.connect(self.stopCurrentConn)
        quitButton.clicked.connect(self.close)
        self.webSocket.connected.connect(self.websocketConnect)
        self.webSocket.disconnected.connect(self.webSocketDisconnect)
        self.webSocket.error.connect(self.displayError)
        self.webSocket.textMessageReceived.connect(
            self.webSocketMessageReceived)
        self.sendTextEdit.textChanged.connect(self.enableSendMessageButton)
        self.sendMsgbutton.clicked.connect(self.sendMsgToServer)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(taskCodeLabel, 2, 0)
        mainLayout.addWidget(self.taskLineEdit, 2, 1)
        mainLayout.addWidget(self.statusLabel, 3, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 4, 0, 1, 2)
        mainLayout.addWidget(self.serverMsgLable, 5, 0)
        mainLayout.addWidget(self.serverLineEdit, 5, 1, 1, 1)
        mainLayout.addWidget(self.sendMsgLabel, 6, 0)
        mainLayout.addWidget(self.sendTextEdit, 6, 1)
        mainLayout.addWidget(self.sendMsgbutton, 7, 0, 1, 5)
        self.serverLineEdit.setEnabled(False)
        self.serverMsgLable.setVisible(False)
        self.serverLineEdit.setVisible(False)
        self.sendMsgLabel.setVisible(False)
        self.sendTextEdit.setVisible(False)
        self.sendMsgbutton.setEnabled(False)
        self.sendMsgbutton.setVisible(False)
        self.setLayout(mainLayout)
        mainLayout.setSpacing(10)
        self.setWindowTitle(self.title)
        self.portLineEdit.setFocus()
        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.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
Esempio n. 21
0
 def mock_fromName(host):
     info = QHostInfo()
     if host == "known.domain":
         info.setAddresses([QHostAddress("1.2.3.4")])
     return info
Esempio n. 22
0
    def __processReadyRead(self):
        """
        Private slot to handle the readyRead signal.
        """
        if self.__state == Connection.WaitingForGreeting:
            if not self.__readProtocolHeader():
                return
            if self.__currentDataType != Connection.Greeting:
                self.abort()
                return
            self.__state = Connection.ReadingGreeting
        
        if self.__state == Connection.ReadingGreeting:
            if not self.__hasEnoughData():
                return
            
            self.__buffer = QByteArray(
                self.read(self.__numBytesForCurrentDataType))
            if self.__buffer.size() != self.__numBytesForCurrentDataType:
                self.abort()
                return
            
            try:
                user, serverPort = \
                    str(self.__buffer, encoding="utf-8").split(":")
            except ValueError:
                self.abort()
                return
            self.__serverPort = int(serverPort)
            
            hostInfo = QHostInfo.fromName(self.peerAddress().toString())
            self.__username = "******".format(
                user,
                hostInfo.hostName(),
                self.peerPort()
            )
            self.__currentDataType = Connection.Undefined
            self.__numBytesForCurrentDataType = 0
            self.__buffer.clear()
            
            if not self.isValid():
                self.abort()
                return
            
            bannedName = "{0}@{1}".format(
                user,
                hostInfo.hostName(),
            )
            Preferences.syncPreferences()
            if bannedName in Preferences.getCooperation("BannedUsers"):
                self.rejected.emit(self.tr(
                    "* Connection attempted by banned user '{0}'.")
                    .format(bannedName))
                self.abort()
                return
            
            if self.__serverPort != self.peerPort() and \
               not Preferences.getCooperation("AutoAcceptConnections"):
                # don't ask for reverse connections or
                # if we shall accept automatically
                res = E5MessageBox.yesNo(
                    None,
                    self.tr("New Connection"),
                    self.tr("""<p>Accept connection from """
                            """<strong>{0}@{1}</strong>?</p>""").format(
                        user, hostInfo.hostName()),
                    yesDefault=True)
                if not res:
                    self.abort()
                    return

            if self.__client is not None:
                chatWidget = self.__client.chatWidget()
                if chatWidget is not None and not chatWidget.isVisible():
                    e5App().getObject(
                        "UserInterface").activateCooperationViewer()
            
            if not self.__isGreetingMessageSent:
                self.__sendGreetingMessage()
            
            self.__pingTimer.start()
            self.__pongTime.start()
            self.__state = Connection.ReadyForUse
            self.readyForUse.emit()
        
        while self.bytesAvailable():
            if self.__currentDataType == Connection.Undefined:
                if not self.__readProtocolHeader():
                    return
            
            if not self.__hasEnoughData():
                return
            
            self.__processData()
Esempio n. 23
0
 def mock_fromName(host):
     info = QHostInfo()
     if host == "known.domain":
         info.setAddresses([QHostAddress("1.2.3.4")])
     return info
Esempio n. 24
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ""

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != "":
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != "":
                self.hostCombo.addItem(name + "." + domain)

        if name != "localhost":
            self.hostCombo.addItem("localhost")

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.")

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

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

        self.tcpSocket = QTcpSocket(self)

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.tcpSocket.readyRead.connect(self.readFortune)
        self.tcpSocket.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.portLineEdit.setFocus()

        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.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
Esempio n. 25
0
    def __processReadyRead(self):
        """
        Private slot to handle the readyRead signal.
        """
        if self.__state == Connection.WaitingForGreeting:
            if not self.__readProtocolHeader():
                return
            if self.__currentDataType != Connection.Greeting:
                self.abort()
                return
            self.__state = Connection.ReadingGreeting

        if self.__state == Connection.ReadingGreeting:
            if not self.__hasEnoughData():
                return

            self.__buffer = QByteArray(
                self.read(self.__numBytesForCurrentDataType))
            if self.__buffer.size() != self.__numBytesForCurrentDataType:
                self.abort()
                return

            try:
                user, serverPort = \
                    str(self.__buffer, encoding="utf-8").split(":")
            except ValueError:
                self.abort()
                return
            self.__serverPort = int(serverPort)

            hostInfo = QHostInfo.fromName(self.peerAddress().toString())
            self.__username = "******".format(user, hostInfo.hostName(),
                                                   self.peerPort())
            self.__currentDataType = Connection.Undefined
            self.__numBytesForCurrentDataType = 0
            self.__buffer.clear()

            if not self.isValid():
                self.abort()
                return

            bannedName = "{0}@{1}".format(
                user,
                hostInfo.hostName(),
            )
            Preferences.syncPreferences()
            if bannedName in Preferences.getCooperation("BannedUsers"):
                self.rejected.emit(
                    self.tr("* Connection attempted by banned user '{0}'.").
                    format(bannedName))
                self.abort()
                return

            if self.__serverPort != self.peerPort() and \
               not Preferences.getCooperation("AutoAcceptConnections"):
                # don't ask for reverse connections or
                # if we shall accept automatically
                res = E5MessageBox.yesNo(
                    None,
                    self.tr("New Connection"),
                    self.tr("""<p>Accept connection from """
                            """<strong>{0}@{1}</strong>?</p>""").format(
                                user, hostInfo.hostName()),
                    yesDefault=True)
                if not res:
                    self.abort()
                    return

            if self.__client is not None:
                chatWidget = self.__client.chatWidget()
                if chatWidget is not None and not chatWidget.isVisible():
                    e5App().getObject(
                        "UserInterface").activateCooperationViewer()

            if not self.__isGreetingMessageSent:
                self.__sendGreetingMessage()

            self.__pingTimer.start()
            self.__pongTime.start()
            self.__state = Connection.ReadyForUse
            self.readyForUse.emit()

        while self.bytesAvailable():
            if self.__currentDataType == Connection.Undefined:
                if not self.__readProtocolHeader():
                    return

            if not self.__hasEnoughData():
                return

            self.__processData()