在使用Python
的webscokets
库的时候,按照互联网上启动服务的代码是
#!/usr/bin/env python
import asyncio
from websockets import serve
async def echo(websocket, path):
async for message in websocket:
await websocket.send(f"Path: Message: {message}")
async def main():
async with serve(echo, "localhost", 8765):
await asyncio.get_running_loop().create_future() # run forever
asyncio.run(main())
实则报错,说明echo这个回调函数不能加path
参数,错误详情如下:
connection handler failed
Traceback (most recent call last):
File "E:\python_web_termnal\.venv\lib\site-packages\websockets\asyncio\server.py", line 373, in conn_handler
await self.handler(connection)
TypeError: echo() missing 1 required positional argument: 'path'
在官网找到最新的实例为
#!/usr/bin/env python
"""Echo server using the asyncio API."""
import asyncio
from websockets.asyncio.server import serve
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main():
async with serve(echo, "localhost", 8765) as server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())
明显看到没有了path
参数,个人感觉是不是最新修改了api原因,最后经过折腾找到了获取path的方法:websocket.request.path
即代码为
#!/usr/bin/env python
import asyncio
from websockets import serve
async def echo(websocket):
print(websocket.request.path)
async for message in websocket:
await websocket.send(f"Path: Message: {message}")
async def main():
async with serve(echo, "localhost", 8765):
await asyncio.get_running_loop().create_future() # run forever
asyncio.run(main())
得到预期输出: