简体   繁体   English

Python3 和 asyncio:如何将 websocket 服务器实现为 asyncio 实例?

[英]Python3 and asyncio: how to implement websocket server as asyncio instance?

I have multiple servers, each server is instance returning by asyncio.start_server.我有多个服务器,每个服务器都是由 asyncio.start_server 返回的实例。 I need my web_server to works with websockets, to have possibility getting data using my javascript client.我需要我的 web_server 与 websockets 一起工作,以便有可能使用我的 javascript 客户端获取数据。 As I can see, asyncio do not provide websockets, only tcp sockets.正如我所见,asyncio 不提供 websockets,只提供 tcp sockets。 Maybe I missed something ?也许我错过了什么? I want to implement websocket server that I can using in asyncio.gather like below:我想实现我可以在 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()

I do not want to use aiohttp cause if using like in code above aiohttp just blocks another tasks.我不想使用 aiohttp 因为如果在 aiohttp 上面的代码中使用 like 只会阻止另一个任务。 I need something that will be non-blocking and that will have access to data of another servers (login and world).我需要一些非阻塞的东西,并且可以访问另一台服务器的数据(登录和世界)。 Does it possible with asyncio ? asyncio 可以吗? Does asyncio provide something like websockets ? asyncio 是否提供类似 websockets 的东西? How to implement websocket server for using in asyncio.gather ?如何实现在 asyncio.gather 中使用的 websocket 服务器?

Well, finally I've implemented WebServer for using in another thread with asyncio.好吧,最后我实现了 WebServer,以便在另一个带有 asyncio 的线程中使用。 The code (WebServer code):代码(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)

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)
    )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM