Python3 和 asyncio:如何将 websocket 服务器实现为 asyncio 实例? [英] Python3 and asyncio: how to implement websocket server as asyncio instance?
问题描述
我有多个服务器,每个服务器都是由 asyncio.start_server 返回的实例.我需要我的 web_server 与 websockets 一起工作,以便有可能使用我的 javascript 客户端获取数据.正如我所见,asyncio 不提供 websockets,只提供 tcp sockets.也许我错过了什么?我想实现我可以在 asyncio.gather 中使用的 websocket 服务器,如下所示:
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 javascript client. As I can see, asyncio do not provide websockets, only tcp sockets. Maybe I missed something ? I want to implement websocket server that I can using in asyncio.gather like below:
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 上面的代码中使用 like 只会阻止另一个任务.我需要一些非阻塞的东西,并且可以访问另一台服务器的数据(登录和世界).asyncio 可以吗?asyncio 是否提供类似 websockets 的东西?如何实现在 asyncio.gather 中使用的 websocket 服务器?
I do not want to use aiohttp cause if using like in code above aiohttp just blocks another tasks. 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 ? Does asyncio provide something like websockets ? How to implement websocket server for using in asyncio.gather ?
推荐答案
好吧,我终于实现了 WebServer 以便在另一个线程中使用 asyncio.代码(WebServer代码):
Well, finally I've implemented WebServer for using in another thread with asyncio. The code (WebServer code):
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:如何将 websocket 服务器实现为 asyncio 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!