PyQt和WebSocket客户端。后台监听WebSocket
我有一个用PyQt做的图形界面应用程序。这个应用程序在启动后应该打开一个主窗口。
这个应用程序需要监听一个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了。
我需要在“后台”监听websocket吗?你能帮我吗?
PS:(抱歉我的英语)
1 个回答
3
谢谢你,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_())