1
2#############################################################################
3##
4## Copyright (C) 2013 Riverbank Computing Limited.
5## Copyright (C) 2016 The Qt Company Ltd.
6## Contact: http://www.qt.io/licensing/
7##
8## This file is part of the Qt for Python examples of the Qt Toolkit.
9##
10## $QT_BEGIN_LICENSE:BSD$
11## You may use this file under the terms of the BSD license as follows:
12##
13## "Redistribution and use in source and binary forms, with or without
14## modification, are permitted provided that the following conditions are
15## met:
16##   * Redistributions of source code must retain the above copyright
17##     notice, this list of conditions and the following disclaimer.
18##   * Redistributions in binary form must reproduce the above copyright
19##     notice, this list of conditions and the following disclaimer in
20##     the documentation and/or other materials provided with the
21##     distribution.
22##   * Neither the name of The Qt Company Ltd nor the names of its
23##     contributors may be used to endorse or promote products derived
24##     from this software without specific prior written permission.
25##
26##
27## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
38##
39## $QT_END_LICENSE$
40##
41#############################################################################
42
43"""PySide2 port of the network/fortuneclient example from Qt v5.x"""
44
45from PySide2 import QtCore, QtGui, QtWidgets, QtNetwork
46
47
48class Client(QtWidgets.QDialog):
49    def __init__(self, parent=None):
50        super(Client, self).__init__(parent)
51
52        self.blockSize = 0
53        self.currentFortune = ''
54
55        hostLabel = QtWidgets.QLabel("&Server name:")
56        portLabel = QtWidgets.QLabel("S&erver port:")
57
58        self.hostLineEdit = QtWidgets.QLineEdit('Localhost')
59        self.portLineEdit = QtWidgets.QLineEdit()
60        self.portLineEdit.setValidator(QtGui.QIntValidator(1, 65535, self))
61
62        hostLabel.setBuddy(self.hostLineEdit)
63        portLabel.setBuddy(self.portLineEdit)
64
65        self.statusLabel = QtWidgets.QLabel("This examples requires that you run "
66                "the Fortune Server example as well.")
67
68        self.getFortuneButton = QtWidgets.QPushButton("Get Fortune")
69        self.getFortuneButton.setDefault(True)
70        self.getFortuneButton.setEnabled(False)
71
72        quitButton = QtWidgets.QPushButton("Quit")
73
74        buttonBox = QtWidgets.QDialogButtonBox()
75        buttonBox.addButton(self.getFortuneButton,
76                QtWidgets.QDialogButtonBox.ActionRole)
77        buttonBox.addButton(quitButton, QtWidgets.QDialogButtonBox.RejectRole)
78
79        self.tcpSocket = QtNetwork.QTcpSocket(self)
80
81        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
82        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
83        self.getFortuneButton.clicked.connect(self.requestNewFortune)
84        quitButton.clicked.connect(self.close)
85        self.tcpSocket.readyRead.connect(self.readFortune)
86        self.tcpSocket.error.connect(self.displayError)
87
88        mainLayout = QtWidgets.QGridLayout()
89        mainLayout.addWidget(hostLabel, 0, 0)
90        mainLayout.addWidget(self.hostLineEdit, 0, 1)
91        mainLayout.addWidget(portLabel, 1, 0)
92        mainLayout.addWidget(self.portLineEdit, 1, 1)
93        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
94        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
95        self.setLayout(mainLayout)
96
97        self.setWindowTitle("Fortune Client")
98        self.portLineEdit.setFocus()
99
100    def requestNewFortune(self):
101        self.getFortuneButton.setEnabled(False)
102        self.blockSize = 0
103        self.tcpSocket.abort()
104        self.tcpSocket.connectToHost(self.hostLineEdit.text(),
105                int(self.portLineEdit.text()))
106
107    def readFortune(self):
108        instr = QtCore.QDataStream(self.tcpSocket)
109        instr.setVersion(QtCore.QDataStream.Qt_4_0)
110
111        if self.blockSize == 0:
112            if self.tcpSocket.bytesAvailable() < 2:
113                return
114
115            self.blockSize = instr.readUInt16()
116
117        if self.tcpSocket.bytesAvailable() < self.blockSize:
118            return
119
120        nextFortune = instr.readString()
121
122        try:
123            # Python v3.
124            nextFortune = str(nextFortune, encoding='ascii')
125        except TypeError:
126            # Python v2.
127            pass
128
129        if nextFortune == self.currentFortune:
130            QtCore.QTimer.singleShot(0, self.requestNewFortune)
131            return
132
133        self.currentFortune = nextFortune
134        self.statusLabel.setText(self.currentFortune)
135        self.getFortuneButton.setEnabled(True)
136
137    def displayError(self, socketError):
138        if socketError == QtNetwork.QAbstractSocket.RemoteHostClosedError:
139            pass
140        elif socketError == QtNetwork.QAbstractSocket.HostNotFoundError:
141            QtWidgets.QMessageBox.information(self, "Fortune Client",
142                    "The host was not found. Please check the host name and "
143                    "port settings.")
144        elif socketError == QtNetwork.QAbstractSocket.ConnectionRefusedError:
145            QtWidgets.QMessageBox.information(self, "Fortune Client",
146                    "The connection was refused by the peer. Make sure the "
147                    "fortune server is running, and check that the host name "
148                    "and port settings are correct.")
149        else:
150            QtWidgets.QMessageBox.information(self, "Fortune Client",
151                    "The following error occurred: %s." % self.tcpSocket.errorString())
152
153        self.getFortuneButton.setEnabled(True)
154
155    def enableGetFortuneButton(self):
156        self.getFortuneButton.setEnabled(bool(self.hostLineEdit.text() and
157                self.portLineEdit.text()))
158
159
160if __name__ == '__main__':
161
162    import sys
163
164    app = QtWidgets.QApplication(sys.argv)
165    client = Client()
166    client.show()
167    sys.exit(client.exec_())
168