使用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
英文地址,請注明出處:http://en.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;不用…