Python3 和 asyncio : how to implement websocket server as asyncio instance?

标签 python python-3.x websocket python-3.5 python-asyncio

我有多个服务器,每个服务器都是 asyncio.start_server 返回的实例。我需要我的 web_server 与 websockets 一起使用,以便能够使用我的 javascript 客户端获取数据。正如我所看到的,asyncio 不提供 websocket,只提供 tcp 套接字。也许我错过了什么?我想实现可以在 asyncio.gather 中使用的 websocket 服务器,如下所示:

    loop = asyncio.get_event_loop()

    login_server = LoginServer.create()
    world_server = WorldServer.create()
    web_server   = WebServer.create()

    loop.run_until_complete(
        asyncio.gather(
            login_server.get_instance(),
            world_server.get_instance(),
            web_server.get_instance()
        )
    )

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    loop.close()

我不想使用 aiohttp,因为如果使用上面代码中的 aiohttp 只会阻塞其他任务。我需要一些非阻塞的东西,并且可以访问其他服务器的数据(登录和世界)。可以使用 asyncio 吗? asyncio 是否提供类似 websockets 的东西?如何实现在 asyncio.gather 中使用的 websocket 服务器?

最佳答案

好吧,最后我实现了 WebServer,以便在另一个线程中使用 asyncio。代码(WebServer代码):

from aiohttp import web


class WebServer(BaseServer):

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

    @staticmethod
    async def handle_connection(self, request: web.web_request):
        ws = web.WebSocketResponse()
        await ws.prepare(request)

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

        return ws

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

以及如何运行:

executor = ProcessPoolExecutor()

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

关于Python3 和 asyncio : how to implement websocket server as asyncio instance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54650760/

相关文章:

python - SQLAlchemy session 错误 : InvalidRequestError

python - 是否可以使用 groupby 拆分 Pandas 数据帧并将每个组与单独的数据帧合并

python - 不使用 pandas 的多列标签编码

c++ - 如何使用 libwebsocket 将 16 位音频数据发送到服务器

python - python statsmodels.tsa.seasonal 中的值错误

python - 忽略在 python 3 中向调用者引发异常

email - Python3 : Send email message containing binary data?

javascript - 使用 WebSocket 进行文件传输

playframework - Reload后在WebSocket Iteratee中 Play Morphia MappingException

python - Google 应用引擎无法实例化超过 Google 应用引擎中 backends.yaml 中定义的后端实例的任务队列