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

基于Python Websockets的客户端程序,能够连接服务端、处理ping/pong、发送订阅请求并保持长连接

以下是一个基于Python Websockets的客户端程序,能够连接服务端、处理ping/pong、发送订阅请求并保持长连接:

import asyncio
import websockets
import json
import time
import logging
import traceback
from datetime import datetime, timedelta# 配置日志
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler("websocket_client.log"),logging.StreamHandler()]
)
logger = logging.getLogger(__name__)class WebSocketClient:def __init__(self, uri, subscribe_message, max_reconnect_attempts=5):self.uri = uriself.subscribe_message = subscribe_messageself.max_reconnect_attempts = max_reconnect_attemptsself.reconnect_delay = 5  # 初始重连延迟(秒)self.last_message_time = time.time()self.connection_active = Falseself.websocket = Noneself.message_counter = 0self.ping_counter = 0self.pong_counter = 0async def connect(self):"""建立WebSocket连接并保持活动状态"""reconnect_attempts = 0while True:try:logger.info(f"Connecting to {self.uri}")async with websockets.connect(self.uri,ping_interval=20,  # 发送底层ping的间隔ping_timeout=15,   # 等待pong的超时时间close_timeout=5    # 关闭超时) as websocket:self.websocket = websocketself.connection_active = Truereconnect_attempts = 0self.reconnect_delay = 5logger.info("Connection established. Sending subscribe message...")await self.send_subscribe()# 启动消息处理任务await self.handle_messages()except (websockets.ConnectionClosed, ConnectionRefusedError) as e:logger.warning(f"Connection closed: {e}")self.connection_active = Falseexcept Exception as e:logger.error(f"Unexpected error: {str(e)}")logger.debug(traceback.format_exc())self.connection_active = Falsefinally:# 重连逻辑if reconnect_attempts 
http://www.dtcms.com/a/257100.html

相关文章:

  • Openwrt基本初始化(安装中文包,磁盘扩容)
  • Python环境搭建竞赛
  • Unity高性能无GC图表
  • 顶顶通AI呼叫软件(大模型电话机器人)介绍
  • 如何卸载幂果画报
  • 【系统分析师】2018年真题:论文及解题思路
  • 仕么是GAN网络和原理和架构
  • 分库分表下的 ID 冲突问题与雪花算法讲解
  • 如何仅用AI开发完整的小程序<6>—让AI对视觉效果进行升级
  • STM32[笔记]--3.数据手册相关
  • VS2019调试进入FFmpeg源码
  • 设备故障预测与健康管理(PHM)的技术跃迁:中讯烛龙工业AI内核解析
  • 【JavaScript】代码整理
  • JVM(10)——详解Parallel垃圾回收器
  • Vue3+TypeScript+Element Plus 表格展开行优化方案
  • C++面试需知——并发与多线程
  • Python打卡训练营Day56
  • es中向量索引的增量更新
  • Unity3D仿星露谷物语开发69之动作声音
  • Go 循环依赖的依赖注入解决方案详解
  • 【论文阅读 | CVPR 2024 |Fusion-Mamba :用于跨模态目标检测】
  • 等等等等等等
  • Python 数据分析与可视化 Day 4 - Pandas 数据筛选与排序操作
  • 1928: 日期差值 codeup
  • I/O 多路复用
  • STM32 CAN位同步、错误处理
  • 数据赋能(308)——合作共享——数据交流
  • 小白的进阶之路系列之十八----人工智能从初步到精通pytorch综合运用的讲解第十一部分
  • 电池模块仿真 - 线性时不变降阶模型
  • 《情感反诈模拟器》2025学习版