Python - Running Autobahn|Python asyncio websocket server in a separate subprocess or thread

后端 未结 3 1815
栀梦
栀梦 2021-02-05 06:08

I have a tkinter based GUI program running in Python 3.4.1. I have several threads running in the program to get JSON data from various urls. I am wanting to add some WebSocket

3条回答
  •  我寻月下人不归
    2021-02-05 06:35

    The answer by @dano might be correct, but creates an new process which is unnessesary in most situations.

    I found this question on Google because i had the same issue myself. I have written an application where i wanted an websocket api to not run on the main thread and this caused your issue.

    I found my alternate sollution by simply reading about event loops on the python documentation and found the asyncio.new_event_loop and asyncio.set_event_loop functions which solved this issue.

    I didn't use AutoBahn but the pypi websockets library, and here's my solution

    import websockets
    import asyncio
    import threading
    
    class WebSocket(threading.Thread):    
        @asyncio.coroutine
        def handler(self, websocket, path):
            name = yield from websocket.recv()
            print("< {}".format(name))
            greeting = "Hello {}!".format(name)
            yield from websocket.send(greeting)
            print("> {}".format(greeting))
    
        def run(self):
            start_server = websockets.serve(self.handler, '127.0.0.1', 9091)
            eventloop = asyncio.new_event_loop()
            asyncio.set_event_loop(eventloop)
            eventloop.run_until_complete(start_server)
            eventloop.run_forever()
    
    if __name__ == "__main__":
        ws = WebSocket()
        ws.start()
    

提交回复
热议问题