from PyQt5.QtCore import QThread, QObject, pyqtSlot
from PyQt5.QtWidgets import QMainWindow, QApplication
import asyncio
import websockets
class ExampleWorker(QObject):
def __init__(self):
super().__init__()
@pyqtSlot()
def start(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(websockets.serve(self.echo, 'localhost', 8765))
self.loop.run_forever()
async def echo(self, websocket, path):
async for message in websocket:
await websocket.send(message)
class Example(QMainWindow):
def __init__(self):
self.app = QApplication([])
super().__init__()
self.obj = ExampleWorker()
self.thread = QThread()
self.obj.moveToThread(self.thread)
self.thread.started.connect(self.obj.start)
self.thread.start()
self.show()
self.app.exec_()
def closeEvent(self, event):
self.thread.quit()
self.thread.wait()
Example()