Esempio n. 1
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()
Esempio n. 2
0
class Client(QDialog):
    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()

    def enableSendMessageButton(self):
        self.sendMsgbutton.setEnabled(self.sendTextEdit.toPlainText() != '')

    def sendMsgToServer(self):
        message = self.sendTextEdit.toPlainText()
        self.webSocket.sendTextMessage(message)

    def CreateNewConn(self):
        '''
        连接按钮点击事件,尝试进行连接 QWebSocket
        :return:
        '''
        self.getFortuneButton.setText("连接中,请等待")
        self.getFortuneButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.webSocket.abort()
        host = self.hostCombo.currentText()
        port = self.portLineEdit.text()
        task_code = self.taskLineEdit.text()
        format_url = 'ws://{}:{}/websocket/master/{}/{}'.format(
            host, port, 'xiangjqjngkljjkl12345', task_code)
        print(format_url)
        request_url = QUrl(format_url)
        self.webSocket.open(request_url)

    def stopCurrentConn(self):
        if self.webSocket is not None and self.webSocket.isValid():
            print('终止连接')
            self.getFortuneButton.setEnabled(True)
            self.stopButton.setEnabled(False)
            self.webSocket.close(QWebSocketProtocol.CloseCodeNormal,
                                 reason='终止连接')
            self.webSocket.close()

    def displayError(self, socketError):
        if socketError == QAbstractSocket.RemoteHostClosedError:
            pass
        elif socketError == QAbstractSocket.HostNotFoundError:
            QMessageBox.information(self, self.title, "找不到主机。请检查主机名和端口设置")
        elif socketError == QAbstractSocket.ConnectionRefusedError:
            QMessageBox.information(
                self, self.title, '''
            连接被同伴拒绝了。确保服务器正在运行,并检查主机名端口设置正确
            ''')
        else:
            QMessageBox.information(
                self, self.title, "出现下列错误: %s." % self.webSocket.errorString())

        self.getFortuneButton.setEnabled(True)
        self.getFortuneButton.setText("重新连接")

    def enableGetFortuneButton(self):
        self.getFortuneButton.setEnabled(
            (self.networkSession is None or self.networkSession.isOpen())
            and self.hostCombo.currentText() != ''
            and self.portLineEdit.text() != ''
            and self.taskLineEdit.text() != '')

    def sessionOpened(self):
        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.statusLabel.setText("This examples requires that you run the "
                                 "Fortune Server example as well.")
        self.enableGetFortuneButton()

    def websocketConnect(self):
        print("websocketConnect")
        self.statusLabel.setText('连接成功')
        self.serverMsgLable.setVisible(True)
        self.serverLineEdit.setVisible(True)
        self.sendMsgLabel.setVisible(True)
        self.sendTextEdit.setVisible(True)
        self.sendMsgbutton.setVisible(True)

    def webSocketDisconnect(self):
        self.statusLabel.setText('连接退出')
        self.getFortuneButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.serverMsgLable.setVisible(False)
        self.serverLineEdit.setVisible(False)
        self.sendMsgLabel.setVisible(False)
        self.sendTextEdit.setVisible(False)
        self.sendMsgbutton.setVisible(False)
        self.getFortuneButton.setText('重新连接')
        print("disconnected")

    def webSocketMessageReceived(self, p_str):
        self.serverLineEdit.setText('接收到消息' + p_str)
        self.statusLabel.setText('接收到消息' + p_str)
        print("webSocketMessageReceived" + p_str)
Esempio n. 3
0
class Client(QDialog):
    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()

    def requestNewFortune(self):
        self.getFortuneButton.setEnabled(False)
        self.blockSize = 0
        self.tcpSocket.abort()
        self.tcpSocket.connectToHost(self.hostCombo.currentText(), int(self.portLineEdit.text()))

    def readFortune(self):
        instr = QDataStream(self.tcpSocket)
        instr.setVersion(QDataStream.Qt_4_0)

        if self.blockSize == 0:
            if self.tcpSocket.bytesAvailable() < 2:
                return

            self.blockSize = instr.readUInt16()

        if self.tcpSocket.bytesAvailable() < self.blockSize:
            return

        nextFortune = instr.readQString()
        if nextFortune == self.currentFortune:
            QTimer.singleShot(0, self.requestNewFortune)
            return

        self.currentFortune = nextFortune
        self.statusLabel.setText(self.currentFortune)
        self.getFortuneButton.setEnabled(True)

    def displayError(self, socketError):
        if socketError == QAbstractSocket.RemoteHostClosedError:
            pass
        elif socketError == QAbstractSocket.HostNotFoundError:
            QMessageBox.information(
                self, "Fortune Client", "The host was not found. Please check the host name and " "port settings."
            )
        elif socketError == QAbstractSocket.ConnectionRefusedError:
            QMessageBox.information(
                self,
                "Fortune Client",
                "The connection was refused by the peer. Make sure the "
                "fortune server is running, and check that the host name "
                "and port settings are correct.",
            )
        else:
            QMessageBox.information(
                self, "Fortune Client", "The following error occurred: %s." % self.tcpSocket.errorString()
            )

        self.getFortuneButton.setEnabled(True)

    def enableGetFortuneButton(self):
        self.getFortuneButton.setEnabled(
            (self.networkSession is None or self.networkSession.isOpen())
            and self.hostCombo.currentText() != ""
            and self.portLineEdit.text() != ""
        )

    def sessionOpened(self):
        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.statusLabel.setText("This examples requires that you run the " "Fortune Server example as well.")

        self.enableGetFortuneButton()
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()
Esempio n. 5
0
class Client(QDialog):
    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()

    def requestNewFortune(self):
        self.getFortuneButton.setEnabled(False)
        self.blockSize = 0
        self.tcpSocket.abort()
        self.tcpSocket.connectToHost(self.hostCombo.currentText(),
                                     int(self.portLineEdit.text()))

    def readFortune(self):
        instr = QDataStream(self.tcpSocket)
        instr.setVersion(QDataStream.Qt_4_0)

        if self.blockSize == 0:
            if self.tcpSocket.bytesAvailable() < 2:
                return

            self.blockSize = instr.readUInt16()

        if self.tcpSocket.bytesAvailable() < self.blockSize:
            return

        nextFortune = instr.readQString()
        if nextFortune == self.currentFortune:
            QTimer.singleShot(0, self.requestNewFortune)
            return

        self.currentFortune = nextFortune
        self.statusLabel.setText(self.currentFortune)
        self.getFortuneButton.setEnabled(True)

    def displayError(self, socketError):
        if socketError == QAbstractSocket.RemoteHostClosedError:
            pass
        elif socketError == QAbstractSocket.HostNotFoundError:
            QMessageBox.information(
                self, "Fortune Client",
                "The host was not found. Please check the host name and "
                "port settings.")
        elif socketError == QAbstractSocket.ConnectionRefusedError:
            QMessageBox.information(
                self, "Fortune Client",
                "The connection was refused by the peer. Make sure the "
                "fortune server is running, and check that the host name "
                "and port settings are correct.")
        else:
            QMessageBox.information(
                self, "Fortune Client", "The following error occurred: %s." %
                self.tcpSocket.errorString())

        self.getFortuneButton.setEnabled(True)

    def enableGetFortuneButton(self):
        self.getFortuneButton.setEnabled(
            (self.networkSession is None or self.networkSession.isOpen())
            and self.hostCombo.currentText() != ''
            and self.portLineEdit.text() != '')

    def sessionOpened(self):
        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.statusLabel.setText("This examples requires that you run the "
                                 "Fortune Server example as well.")

        self.enableGetFortuneButton()