WebSocket服务端报错TypeError: handle_connection()缺少必填参数'path'的解决方法咨询
WebSocket服务端报错TypeError: handle_connection()缺少必填参数'path'的解决方法咨询
看起来你遇到的问题是因为websockets库的版本差异导致的处理器函数参数不匹配!
从服务端的报错信息能明确看到:TypeError: handle_connection() missing 1 required positional argument: 'path',这说明websockets.serve调用你的handle_connection函数时,只传递了一个参数(WebSocket连接对象),但你的函数定义里要求两个参数(websocket和path),所以触发了这个错误,进而导致客户端收到1011内部错误。
解决方法很简单:
修改服务端的handle_connection函数定义,去掉多余的path参数即可。
修正后的server.py代码如下:
import asyncio import websockets from websockets.exceptions import ConnectionClosedError async def handle_connection(websocket): # 移除多余的path参数 print("[+] Client connected.") try: async for message in websocket: print(f"[*] Message received: {message}") response = f"Server Echo: {message}" await websocket.send(response) # Send response to client except ConnectionClosedError as e: print(f"[-] Connection closed by client: {e}") except Exception as e: print(f"[!] Unexpected error: {e}") async def main(): server = await websockets.serve(handle_connection, "0.0.0.0", 9000) print("[+] WebSocket server started on port 9000...") await server.wait_closed() if __name__ == "__main__": asyncio.run(main())
补充说明:
在旧版本的websockets库中,serve方法的处理器函数需要接收websocket和path两个参数,但在较新的版本(比如11.0及以上)中,path参数已经被移除了——现在可以通过websocket.path属性来获取请求路径,所以不需要再把它作为参数传入处理器函数。
你只需要把服务端的函数改成单参数形式,再重新启动服务端,客户端就能正常和服务端通信啦!
备注:内容来源于stack exchange,提问作者user29781920
相关产品推荐
相关产品推荐

