Python 3;Websockets 服务器和 HTTP 服务器 - run_forever 和serve_forever

use*_*041 7 python http websocket server

我正在尝试在同一个 python 应用程序中运行 websockets 服务器和 http 服务器。看起来我正在尝试运行两个永远循环,但第二个循环没有被激活。关于如何让这两个服务器运行有什么建议吗?

httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)

httpd.serve_forever()
asyncio.get_event_loop().run_until_complete(
    websockets.serve(echo, 'localhost', 8001))
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

Cos*_*imo 10

这是使用一台服务器同时提供 websocket 和 http 请求的一种方法。与您建议的唯一区别是两个处理程序侦听同一端口。

我认为可以通过定义两个aiohttp应用程序来监听单独的端口。然而,无论如何,您都需要一个支持异步的 HTTP 服务器。AFAIKHTTPServer不支持异步,因此您提出的解决方案无法工作,因为您将基于异步的服务器 ( websockets.serve) 与非异步服务器 ( HTTPServer) 混合在一起。

#!/usr/bin/python3.7

import aiohttp
from aiohttp import web, WSCloseCode
import asyncio


async def http_handler(request):
    return web.Response(text='Hello, world')


async def websocket_handler(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            if msg.data == 'close':
                await ws.close()
            else:
                await ws.send_str('some websocket message payload')
        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' % ws.exception())

    return ws


def create_runner():
    app = web.Application()
    app.add_routes([
        web.get('/',   http_handler),
        web.get('/ws', websocket_handler),
    ])
    return web.AppRunner(app)


async def start_server(host="127.0.0.1", port=1337):
    runner = create_runner()
    await runner.setup()
    site = web.TCPSite(runner, host, port)
    await site.start()


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(start_server())
    loop.run_forever()
Run Code Online (Sandbox Code Playgroud)