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

【websocket】websocket-client 与 websockets

websocket-client

websocket-client 是 websocket 客户端,提供了对ws低级API的访问。通过导入 websocket 库使用,websocket 库是基于事件驱动的设计模式,通过定义回调函数来处理接收到的消息、错误和连接关闭等事件。
优势:

  • 兼容多个 Python 版本,包括 Python 2.7 和 Python 3.x。
  • 简单易用,入门门槛较低。
  • 提供了基本的 WebSocket 功能,可以满足一般需求。

劣势:

  • 功能相对较少,不支持一些高级特性,如异步操作和性能优化。
"""用 websocket 创建长连接"""
import timeimport websocket
from gevent import threaddef on_message(ws, message):# 处理收到的消息print("Received: " + message)def on_error(ws, error):# 处理错误print("Error: " + str(error))def on_close(ws):# 关闭连接print("Connection closed")def on_open(ws):# 连接成功后的操作def run(*args):# 发送心跳包或其他持续性操作while True:ws.send("Ping")time.sleep(1)  # 每隔一秒发送一次thread.start_new_thread(run, ())if __name__ == "__main__":# 创建 WebSocket 连接websocket.enableTrace(True)ws = websocket.WebSocketApp('ws://your-websocket-url',on_message=on_message,on_error=on_error,on_close=on_close)ws.on_open = on_open# 运行 WebSocket 客户端ws.run_forever()

websockets

websockets 具有 server端和 client端,采用异步操作模式,与 asyncio 模块无缝集成,可以实现高性能的 WebSocket 服务器和客户端。

python版本仅支持3.6及更高版本

优势:

  • 高性能和可扩展性
  • 提供了丰富的特性:支持心跳包、自定义协议和 SSL/TLS 加密等高级功能。

劣势:

  • 不兼容 Python 2.x 版本。
"""服务端"""
import asyncio
import websocketsasync def handle(ws, path):name = await ws.recv()print(f"接收: {name}")greeting = f"已收到 {name}!"await ws.send(greeting)print(f"发送: {greeting}")if __name__ == '__main__':s = websockets.serve(handle, "127.0.0.1", 9451)event_loop = asyncio.get_event_loop()event_loop.run_until_complete(s)event_loop.run_forever()
"""客户端"""
import asyncio
import websocketsasync def hello():uri = "ws://127.0.0.1:9451"async with websockets.connect(uri) as websocket:name = input("发送: ")await websocket.send(name)greeting = await websocket.recv()print(f"接收: {greeting}")if __name__ == '__main__':event_loop = asyncio.get_event_loop()event_loop.run_until_complete(hello())
http://www.lryc.cn/news/132226.html

相关文章:

  • Qt快速学习(一)--对象,信号和槽
  • Qt6之如何为QDialog添加最大化和最小化按钮
  • 攻防世界-warmup
  • 02__models
  • MyBatis入门配置及CURD实现
  • 《游戏编程模式》学习笔记(五)原型模式 Prototype Pattern
  • ansible案列之LNMP分布式剧本
  • React2023电商项目实战 - 1.项目搭建
  • 数据库连接池(c3p0和德鲁伊)
  • ARM--day6(实现字符、字符串收发的代码和现象,分析RCC、GPIO、UART章节)
  • 2023牛客暑期多校训练营9 B.Semi-Puzzle: Brain Storm
  • mysql中的窗口函数
  • 【双指针】经典数组双指针题LeetCode
  • 极智嘉x吉利汽车 x京东物流,引领汽车行业智慧物流新变革!
  • RK3588平台开发系列讲解(AI 篇)RKNN C API 详细说明
  • 【基础】Android Handler
  • c语言实现MD5算法
  • Apache Doris 2.0.0 特性分析
  • 如何做H5性能测试?
  • 【Docker】Docker Desktop配置资源:cpu、内存等(windows环境下)
  • 8.2.tensorRT高级(3)封装系列-内存管理的封装,内存的复用
  • Keepalived入门指南:实现故障转移和负载均衡
  • cuOSD(CUDA On-Screen Display Library)库的学习
  • c++函数指针基本用法
  • Java创建对象的几种方式
  • Docker实战专栏简介
  • 解放数据库,实时数据同步利器:Alibaba Canal
  • 机器学习基础之《分类算法(3)—模型选择与调优》
  • Datawhale Django后端开发入门 TASK03 QuerySet和Instance、APIVIew
  • Python 网页解析中级篇:深入理解BeautifulSoup库