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/fortuneserver example from Qt v5.x"""
44
45import random
46
47from PySide2 import QtCore, QtWidgets, QtNetwork
48
49
50class Server(QtWidgets.QDialog):
51    def __init__(self, parent=None):
52        super(Server, self).__init__(parent)
53
54        statusLabel = QtWidgets.QLabel()
55        quitButton = QtWidgets.QPushButton("Quit")
56        quitButton.setAutoDefault(False)
57
58        self.tcpServer = QtNetwork.QTcpServer(self)
59        if not self.tcpServer.listen():
60            QtWidgets.QMessageBox.critical(self, "Fortune Server",
61                    "Unable to start the server: %s." % self.tcpServer.errorString())
62            self.close()
63            return
64
65        statusLabel.setText("The server is running on port %d.\nRun the "
66                "Fortune Client example now." % self.tcpServer.serverPort())
67
68        self.fortunes = (
69                "You've been leading a dog's life. Stay off the furniture.",
70                "You've got to think about tomorrow.",
71                "You will be surprised by a loud noise.",
72                "You will feel hungry again in another hour.",
73                "You might have mail.",
74                "You cannot kill time without injuring eternity.",
75                "Computers are not intelligent. They only think they are.")
76
77        quitButton.clicked.connect(self.close)
78        self.tcpServer.newConnection.connect(self.sendFortune)
79
80        buttonLayout = QtWidgets.QHBoxLayout()
81        buttonLayout.addStretch(1)
82        buttonLayout.addWidget(quitButton)
83        buttonLayout.addStretch(1)
84
85        mainLayout = QtWidgets.QVBoxLayout()
86        mainLayout.addWidget(statusLabel)
87        mainLayout.addLayout(buttonLayout)
88        self.setLayout(mainLayout)
89
90        self.setWindowTitle("Fortune Server")
91
92    def sendFortune(self):
93        block = QtCore.QByteArray()
94        out = QtCore.QDataStream(block, QtCore.QIODevice.WriteOnly)
95        out.setVersion(QtCore.QDataStream.Qt_4_0)
96        out.writeUInt16(0)
97        fortune = self.fortunes[random.randint(0, len(self.fortunes) - 1)]
98
99        out.writeString(fortune)
100        out.device().seek(0)
101        out.writeUInt16(block.size() - 2)
102
103        clientConnection = self.tcpServer.nextPendingConnection()
104        clientConnection.disconnected.connect(clientConnection.deleteLater)
105
106        clientConnection.write(block)
107        clientConnection.disconnectFromHost()
108
109
110if __name__ == '__main__':
111
112    import sys
113
114    app = QtWidgets.QApplication(sys.argv)
115    server = Server()
116    random.seed(None)
117    sys.exit(server.exec_())
118