Skip to content Skip to sidebar Skip to footer

Python3 And Asyncio: How To Implement Websocket Server As Asyncio Instance?

I have multiple servers, each server is instance returning by asyncio.start_server. I need my web_server to works with websockets, to have possibility getting data using my javascr

Solution 1:

Well, finally I've implemented WebServer for using in another thread with asyncio. The code (WebServer code):

from aiohttp import web


classWebServer(BaseServer):

    def__init__(self, host, port):
        super().__init__(host, port)

    @staticmethodasyncdefhandle_connection(self, request: web.web_request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)

        asyncfor msg in ws:
            Logger.debug('[Web Server]: {}'.format(msg))

        return ws

    @staticmethoddefrun():
        app = web.Application()
        web.run_app(app, host=Connection.WEB_SERVER_HOST.value, port=Connection.WEB_SERVER_PORT.value)

And how to run:

executor = ProcessPoolExecutor()

loop.run_until_complete(
    asyncio.gather(
        login_server.get_instance(),
        world_server.get_instance(),
        loop.run_in_executor(executor, WebServer.run)
    )
)

Post a Comment for "Python3 And Asyncio: How To Implement Websocket Server As Asyncio Instance?"