【问题标题】:Running server in background, while app does something else在后台运行服务器,而应用程序执行其他操作
【发布时间】:2019-08-24 03:18:45
【问题描述】:

我正在尝试制作一个桌面应用程序,作为运行服务器的触发器。该应用程序(服务器)还将从客户端获取数据并将它们保存在服务器的计算机中。

我已经用flask和socketio在python中制作了服务器。客户也在工作。所以现在我要为服务器制作 GUI,以便非 IT 人员可以运行此服务器。

所以我在 runServer 函数(单击“运行服务器”时调用)中注意到它确实有效并且运行了服务器。但是,当服务器正在运行时,我不能做任何其他事情。所以我尝试使用打印语句进行测试。

        print('hello')
        self.sio.run(self.app, host = '0.0.0.0', port = 8090) #running the server         
        print('hello again')

'hello' 打印出来了,但是 'hello again' 没有打印出来

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.app = Flask(__name__)
        self.sio = SocketIO(self.app)
        self.port = 8090

    def init_ui(self):
        self.runServerButton = QPushButton('Run Server')
        self.runServerButton.clicked.connect(self.runServer)

        self.sayHiButton = QPushButton('Say Hi')
        self.sayHiButton.clicked.connect(self.sayHi)

        self.status = QLabel('Server running\nPlease enter address below to client(s)')
        self.address = QLabel('ipaddress')

        vBox = QVBoxLayout()
        vBox.addWidget(self.runServerButton)
        vBox.addWidget(self.sayHiButton)
        vBox.addWidget(self.status)
        vBox.addWidget(self.address)
        self.status.hide()
        self.address.hide()
        vBox.addStretch()

        self.setLayout(vBox)
        self.setWindowTitle('SDS App')

        self.setGeometry(1000, 500, 200, 200)
        self.show()

    def runServer(self):
        ip = socket.gethostbyname(socket.gethostname())
        self.address.setText(ip)
        self.status.show()
        self.address.show()
        self.runServerButton.setEnabled(False)

        print('hello')
        self.sio.run(self.app, host = '0.0.0.0', port = 8090) #running the server         
        print('hello again')

    @sio.on('hey waddup')
    def on_waduup():
        print('i\'m fine bro')
        status.setText("I'm fine bro")

    def sayHi(self):
        print('Hi!')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    a_window = Window()
    sys.exit(app.exec_())

那么有没有办法在后台运行服务器?或者是否有对此的后门解决方案,例如制作一个运行两个文件的可执行文件;服务器和 gui(必须是另一个客户端)

谢谢!

【问题讨论】:

    标签: sockets flask socket.io pyqt5 flask-socketio


    【解决方案1】:

    sio.run() 调用被阻塞,它启动 Web 服务器并且不返回。为了不阻塞 GUI 应用程序,您需要做的是在后台线程中进行此调用,这样您的按钮处理程序函数就不会被阻塞。应该是这样的:

    def runServer(self):
        # ...
        print('hello')
        self.sio.start_background_task(self.sio.run, host='0.0.0.0', port=8090)
        print('hello again')
    

    start_background_task() 函数的文档:https://flask-socketio.readthedocs.io/en/latest/#flask_socketio.SocketIO.start_background_task

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多