使用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.pswp.cn/news/919294.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/919294.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

机器人相关基础知识

机器人简介下面给出一份机器人方向“从入门到进阶”的极简知识地图&#xff0c;按「数学 → 硬件 → 软件 → 算法 → 应用」五层展开&#xff0c;配合常用开源资源。你可以把它当作“字典”随时查阅。&#x1f539; 1. 数学层&#xff08;所有算法的地基&#xff09;概念一句话…

Windows Server 打开vGPU RDP HEVC编码

查看已安装的驱动[rootlocalhost:~] esxcli software vib list Name Version Vendor Acceptance Level Install Date Platforms ----------------------------- ------------------------------------ ------ -…

OpenAL技术详解:跨平台3D音频API的设计与实践

引言&#xff1a;OpenAL的定位与价值 OpenAL&#xff08;Open Audio Library&#xff09; 是一套跨平台的3D音频应用程序接口&#xff08;API&#xff09;&#xff0c;专为高效渲染多通道三维定位音频而设计。其API风格与编程范式刻意模仿OpenGL&#xff0c;旨在为游戏开发、虚…

重温 K8s 基础概念知识系列五(存储、配置、安全和策略)

文章目录一、存储&#xff08;Storage&#xff09;1.1、Volume1.2、PersistentVolume (PV)1.3、PersistentVolumeClaim (PVC)1.4、StorageClass1.5、PVC 和 PV 的绑定过程&#xff1f;二、配置管理&#xff08;Configuration&#xff09;2.1、ConfigMap2.2、Secret2.3、存活、就…

通过PhotoShop将多张图片整合为gif动画

一、准备图片集合二、导入PS导入PS后点击确定&#xff1a;导入成功&#xff1a;三、添加时间轴勾选创建帧动画&#xff1a;此时时间轴进化为帧动画轴&#xff1a;四、图片集部署在帧动画轴点击帧动画轴右上角的三道横杠&#xff0c;从图层建立帧&#xff1a;此时图片集已经部署…

Easy Rules 规则引擎详解

Easy Rules 规则引擎详解 Easy Rules 是一个轻量级的 Java 规则引擎&#xff0c;它提供了一种简单而强大的方式来定义和执行业务规则。以下是 Easy Rules 的详细介绍&#xff1a; 1. 核心概念 1.1 规则 (Rule) 条件 (Condition): 当条件为 true 时执行动作动作 (Action): 条件满…

优雅设计:打造AI时代的高效后端API接口——领码课堂深度解析

&#x1f4cc; 摘要 后端API接口已经成为软件架构的神经系统。微服务演化、AI渗透、自动化治理……这些趋势迫使我们重新定义接口设计的标准。本文从统一规范、参数校验、异常处理、性能优化四大维度出发&#xff0c;结合领码Spark的接口治理平台与AI赋能实践&#xff0c;构建一…

【VUE】用EmailJS自动发送邮件到网易邮箱

1.注册 EmailJS 账号​​&#xff1a;访问 EmailJS 官网并注册2.添加电子邮件服务​​&#xff1a;在 Dashboard 中点击 "Add New Service"选择 SMTP server填写 SMTP 服务器信息SMTP Host: smtphz.qiye.163.com (网易企业邮箱)SMTP Port: 994 (SSL)User: 你的邮箱Ap…

Ubuntu下载、安装、编译指定版本python

下载 Index of /ftp/python/ https://www.python.org/downloads/ 删除旧的python sudo apt autoremove python sudo apt autoremove python3 安装依赖 sudo apt-get install -y zlib1g-dev libbz2-dev libssl-dev libncurses5-dev \ libsqlite3-dev libreadline-dev tk-d…

如何新建一个自己的虚拟环境

在今天我换了个电脑跑模型的时候&#xff0c;出现了一个问题&#xff1a;C:\ProgramData\Anaconda3\python.exe H:/ywp/project/model/msi_caijian.py Traceback (most recent call last):File "H:/ywp/project/model/msi_caijian.py", line 2, in <module>imp…

(第十八期)图像标签的三个常用属性:width、height、border

&#xff08;第十八期&#xff09;图像标签的三个常用属性&#xff1a;width、height、border 在网页开发中&#xff0c;控制图片尺寸与样式是基础又高频的操作。本文围绕 img 图像标签的三个属性展开&#xff1a;width&#xff08;宽度&#xff09;、height&#xff08;高度&a…

Windows桌面自动化的革命性突破:深度解析Windows-MCP.Net Desktop模块的技术奥秘

"在数字化浪潮中&#xff0c;桌面自动化不再是程序员的专利&#xff0c;而是每个人都能掌握的超能力。" —— 当我第一次接触到Windows-MCP.Net的Desktop模块时&#xff0c;这样的感慨油然而生。 &#x1f3af; 引言&#xff1a;为什么桌面自动化如此重要&#xff1f…

免费又强大的 PDF 编辑器 ——PDF XChange Editor

在日常的学习和工作中&#xff0c;我们经常会与 PDF 文档打交道&#xff0c;然而&#xff0c;PDF 文档的编辑却常常让人抓狂。比如拿到一份 PDF 合同或报告&#xff0c;发现里面有错别字或者需要更新数据&#xff1b;又或者遇到需要填写的 PDF 表单&#xff0c;只能打印出来手写…

Unity引擎播放HLS自适应码率流媒体视频

大家好&#xff0c;我是阿赵。今天来学习一下Unity引擎怎样播放自适应码率视频的方法。 一、 HLS是什么HLS是什么&#xff0c;各位可以自己百度一下。简单的概括&#xff0c;HLS是一种自适应码率流媒体传输协议&#xff0c;实现的是分片下载和动态码率切换。它的原理是把一段视…

Flink 源码系列 - 前言

Flink 源码系列 - 前言 &#x1f680; 为什么要学习 Flink 源码&#xff1f; Apache Flink 作为当前最流行的流式计算框架之一&#xff0c;其源码体系极其庞大。根据统计&#xff0c;Flink 项目包含&#xff1a; Java 文件总行数&#xff1a;232万行有效代码行数&#xff1a…

Rust:实现仅通过索引(序数)导出 DLL 函数的功能

在 Rust 中&#xff0c;可以通过手动控制导出来实现仅通过索引&#xff08;序数&#xff09;导出 DLL 函数的功能。以下是具体方法和完整步骤&#xff1a;解决方案 通过结合 .def 文件&#xff08;模块定义文件&#xff09;和 MSVC 链接器参数来实现函数名隐藏&#xff0c;只暴…

部分网站记录

Gradle多渠道打包[umeng] https://www.jianshu.com/p/8b8fdd37bf26 介绍在app的build.gradle设置produceFlavors&#xff0c;一键打包所有环境的命令 Android 知识图谱 https://upload-images.jianshu.io/upload_images/19956127-1b214e26967dacc6.jpg 百度的语音识别 https:…

【速通】深度学习模型调试系统化方法论:从问题定位到性能优化

深度学习模型调试的系统化方法论&#xff1a;从问题定位到性能优化 文章目录深度学习模型调试的系统化方法论&#xff1a;从问题定位到性能优化摘要1. 引言2. 模型调试的层次化框架2.1 三层调试架构2.2 调试优先级原则3. 系统化调试流程3.1 快速诊断清单3.2 最小可复现案例 (MR…

Nacos-6--Naco的QUIC协议实现高可用的工作原理

QUIC&#xff08;Quick UDP Internet Connections&#xff09;是一种基于UDP的传输层协议&#xff0c;旨在减少网络延迟、提升安全性并优化多路复用能力。它由Google开发&#xff0c;后被IETF标准化为HTTP/3的底层协议。 1、QUIC是什么&#xff1f; QUIC&#xff08;Quick UDP …

python实现pdfs合并

灵感来源于博主正在学408&#xff0c;在搞到视频课对应的ppt.pdf后发现pdf是按小节的&#xff0c;以至于每章有5-10甚至更多&#xff0c;这可太繁琐了&#xff0c;我想要一章一个pdf就可以了&#xff0c;于是浅浅查了几个CSDN发现使用python的要么收费要么要vip&#xff0c;不用…