一尘不染

pyqt和websocket客户端。在后台听websocket

python

我有一个PyQt Gui应用程序。此应用程序有一个主窗口,应在启动后打开。

此应用程序应监听websocket。

我试着解决它是这样的:

...

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    window = Window()
    window.show()

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8080/chatsocket",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
#    ws.on_open = on_open

    ws.run_forever()

    sys.exit(app.exec_())

但是,启动应用程序后,主窗口没有打开。

如果没有“ ws.run_forever()”行,则打开主窗口,但应用程序不侦听websocket。

我需要在“背景”中收听网络套接字吗?你能帮助我吗?

PS :(对不起,我的英语)


阅读 562

收藏
2021-01-20

共1个答案

一尘不染

感谢enginefree。

我做这个

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__()

        self.thread = ListenWebsocket()
        self.thread.start()

...


class ListenWebsocket(QtCore.QThread):
    def __init__(self, parent=None):
        super(ListenWebsocket, self).__init__(parent)

        websocket.enableTrace(True)

        self.WS = websocket.WebSocketApp("ws://localhost:8080/chatsocket",
                                on_message = self.on_message,
                                on_error = self.on_error,
                                on_close = self.on_close)

    def run(self):
        #ws.on_open = on_open

        self.WS.run_forever()


    def on_message(self, ws, message):
        print message

    def on_error(self, ws, error):
        print error

    def on_close(self, ws):
        print "### closed ###"

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    QtGui.QApplication.setQuitOnLastWindowClosed(False)

    window = Window()
    window.show()

    sys.exit(app.exec_())
2021-01-20