How to use websocket running on separate QThread of PyQt application?

29 Views Asked by At

I have a PyQt GUI application that is also running a FastAPI webserver via Uvicorn on a separate thread. This server has a websocket endpoint. I would like to be able to send messages on this WebSocket via a button on the PyQt gui in the main thread.

I tried a Queue system but despite adding to the queue via a signal from the button click, the queue remains empty:

import sys
from queue import Queue

import uvicorn
from fastapi import FastAPI, WebSocket
from PySide2 import QtCore, QtWidgets

app = FastAPI()

queue = Queue()


@app.websocket("/")
async def websocket_endpoint(websocket: WebSocket):

    await websocket.accept()

    if not queue.empty():
        msg = queue.get()
        await websocket.send_text(msg)

    while True:
        incoming = await websocket.receive_text()
        print("Received Message from Client: ", incoming)


class UvicornThread(QtCore.QThread):
    def run(self):
        return uvicorn.run(app)


class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.uvicornThread = UvicornThread()
        self.uvicornThread.start()

        self.mainLayout = QtWidgets.QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.button = QtWidgets.QPushButton("Send Message")
        self.mainLayout.addWidget(self.button)
        self.button.clicked.connect(lambda: queue.put("Sending Message To Client..."))


if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(qapp.exec_())

0

There are 0 best solutions below