当前位置: 首页 > news >正文

使用websockets中的一些问题和解决方法

(1)TypeError: echo() missing 1 required positional argument: 'path'报错

自己写的代码如下:

async def echo(websocket, path):...
async def main():server = await websockets.serve(echo, "0.0.0.0", 666)await server.wait_closed()

在echo中有两个变量websocket和path却在运行时候报错TypeError: echo() missing 1 required positional argument: 'path',查阅资料据说时因为版本的问题,查看源代码也只有一个参数

源码解释如下:

class serve:"""Create a WebSocket server listening on ``host`` and ``port``.Whenever a client connects, the server creates a :class:`ServerConnection`,performs the opening handshake, and delegates to the ``handler`` coroutine.The handler receives the :class:`ServerConnection` instance, which you canuse to send and receive messages.Once the handler completes, either normally or with an exception, the serverperforms the closing handshake and closes the connection.This coroutine returns a :class:`Server` whose API mirrors:class:`asyncio.Server`. Treat it as an asynchronous context manager toensure that the server will be closed::from websockets.asyncio.server import servedef handler(websocket):...# set this future to exit the serverstop = asyncio.get_running_loop().create_future()async with serve(handler, host, port):await stopAlternatively, call :meth:`~Server.serve_forever` to serve requests andcancel it to stop the server::server = await serve(handler, host, port)await server.serve_forever()Args:handler: Connection handler. It receives the WebSocket connection,which is a :class:`ServerConnection`, in argument.host: Network interfaces the server binds to.See :meth:`~asyncio.loop.create_server` for details.port: TCP port the server listens on.See :meth:`~asyncio.loop.create_server` for details.origins: Acceptable values of the ``Origin`` header, for defendingagainst Cross-Site WebSocket Hijacking attacks. Values can be:class:`str` to test for an exact match or regular expressionscompiled by :func:`re.compile` to test against a pattern. Include:obj:`None` in the list if the lack of an origin is acceptable.extensions: List of supported extensions, in order in which theyshould be negotiated and run.subprotocols: List of supported subprotocols, in order of decreasingpreference.select_subprotocol: Callback for selecting a subprotocol amongthose supported by the client and the server. It receives a:class:`ServerConnection` (not a:class:`~websockets.server.ServerProtocol`!) instance and a list ofsubprotocols offered by the client. Other than the first argument,it has the same behavior as the:meth:`ServerProtocol.select_subprotocol<websockets.server.ServerProtocol.select_subprotocol>` method.compression: The "permessage-deflate" extension is enabled by default.Set ``compression`` to :obj:`None` to disable it. See the:doc:`compression guide <../../topics/compression>` for details.process_request: Intercept the request during the opening handshake.Return an HTTP response to force the response or :obj:`None` tocontinue normally. When you force an HTTP 101 Continue response, thehandshake is successful. Else, the connection is aborted.``process_request`` may be a function or a coroutine.process_response: Intercept the response during the opening handshake.Return an HTTP response to force the response or :obj:`None` tocontinue normally. When you force an HTTP 101 Continue response, thehandshake is successful. Else, the connection is aborted.``process_response`` may be a function or a coroutine.server_header: Value of  the ``Server`` response header.It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to:obj:`None` removes the header.open_timeout: Timeout for opening connections in seconds.:obj:`None` disables the timeout.ping_interval: Interval between keepalive pings in seconds.:obj:`None` disables keepalive.ping_timeout: Timeout for keepalive pings in seconds.:obj:`None` disables timeouts.close_timeout: Timeout for closing connections in seconds.:obj:`None` disables the timeout.max_size: Maximum size of incoming messages in bytes.:obj:`None` disables the limit.max_queue: High-water mark of the buffer where frames are received.It defaults to 16 frames. The low-water mark defaults to ``max_queue// 4``. You may pass a ``(high, low)`` tuple to set the high-waterand low-water marks. If you want to disable flow control entirely,you may set it to ``None``, although that's a bad idea.write_limit: High-water mark of write buffer in bytes. It is passed to:meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaultsto 32 KiB. You may pass a ``(high, low)`` tuple to set thehigh-water and low-water marks.logger: Logger for this server.It defaults to ``logging.getLogger("websockets.server")``. See the:doc:`logging guide <../../topics/logging>` for details.create_connection: Factory for the :class:`ServerConnection` managingthe connection. Set it to a wrapper or a subclass to customizeconnection handling.Any other keyword arguments are passed to the event loop's:meth:`~asyncio.loop.create_server` method.For example:* You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.* You can set ``sock`` to provide a preexisting TCP socket. You may call:func:`socket.create_server` (not to be confused with the event loop's:meth:`~asyncio.loop.create_server` method) to create a suitable serversocket and customize it.* You can set ``start_serving`` to ``False`` to start accepting connectionsonly after you call :meth:`~Server.start_serving()` or:meth:`~Server.serve_forever()`."""

可以看到这里例子中也是只用了一个参数

        from websockets.asyncio.server import servedef handler(websocket):...# set this future to exit the serverstop = asyncio.get_running_loop().create_future()async with serve(handler, host, port):await stop

改成一个参数后果然不报错了,并且可以正常运行

(2)websockets.exceptions.ConnectionClosedError: sent 1011 (internal error) keepalive ping timeout; no close frame received

客户端因为心跳超时而被服务器关闭,在自己写的代码中,由于使用input发送数据导致代码阻塞而没能及时响应服务器的心跳,因此被服务器断开连接,这里要使用input的话可以使用asyncio库中将输出放在一个单独的进程中运行,避免阻塞程序

原来代码,有可能阻塞程序导致心跳超时

send_data = input("input data")

修改后代码:

send_data = await asyncio.to_thread(input, "input data:")

http://www.lryc.cn/news/624871.html

相关文章:

  • 华曦达港股IPO观察丨以创新研发为笔,构建AI Home智慧生活新蓝图
  • 8月更新!Windows 10 22H2 64位 五合一版【原版+优化版、版本号:19045.6159】
  • 大模型备案材料—《安全评估报告》撰写指南
  • Zookeeper 在 Kafka 中扮演了什么角色?
  • 8.18作业
  • Python实战--基于Django的企业资源管理系统
  • 嵌入式学习硬件I.MX6ULL(五)按键 中断 GIC OCP原则
  • seuratv4数据结构
  • 软考 系统架构设计师系列知识点之杂项集萃(129)
  • 【数模国奖冲刺】备赛过程中的常见问题
  • Jmeter对图片验证码的处理
  • vue3 + antd实现简单的图片点开可以缩小放大查看
  • 视觉语言导航(4)——强化学习的三种方法 与 优化算法 2.43.4
  • BeeWorks 私有化会议系统:筑牢企业会议安全防线,赋能高效协同
  • Go并发编程-goroutine
  • 私有化部署本地大模型+function Calling+本地数据库
  • 【秋招笔试】2025.08.17字节跳动秋招机考真题
  • 技术赋能安全:智慧工地构建城市建设新防线
  • IB数学课程知识点有哪些?IB数学课程辅导机构怎么选?
  • [系统架构设计师]未来信息综合技术(十一)
  • 【秋招笔试】2025.08.17大疆秋招机考第一套
  • C++ STL容器相关操作的复杂度分析
  • FPGA驱动量子革命:微美全息(NASDAQ:WIMI)实现数字量子计算关键验证
  • 认证授权系统设计
  • redis-集成prometheus监控(k8s)
  • 【K8s】harbor安装与推送镜像
  • 中断线程化
  • 虚幻基础:动作时间窗
  • 徕芬的冰火两重天:增长困局,转型阵痛还是衰落前奏?
  • SQL注入防御