本文介绍了pyqt 和 websocket 客户端.在后台监听 websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 PyQt Gui 应用程序.此应用程序有一个主窗口,应在启动后打开.
I have a PyQt Gui application. This application have a main window that should be open after the start.
这个应用程序应该监听 websocket.
This application should to listen the 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_())
但是,启动应用程序后,主窗口没有打开.
But, after start application the main window was not open.
没有ws.run_forever()"行,主窗口打开,但应用程序不监听 websocket.
Without line "ws.run_forever()" the main window was open but application does not listen websocket.
我需要在后台"监听 websocket?你能帮我吗?
I need listen the websocket in the "background"?Can you help me?
PS:(对不起我的英语)
PS: (Sorry for my english)
推荐答案
感谢 enginefree.
Thanks 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_())
这篇关于pyqt 和 websocket 客户端.在后台监听 websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!