Python WebSocket长连接心跳与短连接的示例

作者:_天枢 时间:2022-08-20 04:05:15 

安装


pip install websocket-client

先来看一下,长连接调用方式:


ws = websocket.WebSocketApp("ws://echo.websocket.org/",
              on_message = on_message,
              on_error = on_error,
              on_close = on_close)
 ws.on_open = on_open
 ws.run_forever()

 长连接,参数介绍:

(1)url: websocket的地址。

(2)header: 客户发送websocket握手请求的请求头,{'head1:value1','head2:value2'}。

(3)on_open:在建立Websocket握手时调用的可调用对象,这个方法只有一个参数,就是该类本身。

(4)on_message:这个对象在接收到服务器返回的消息时调用。有两个参数,一个是该类本身,一个是我们从服务器获取的字符串(utf-8格式)。

(5)on_error:这个对象在遇到错误时调用,有两个参数,第一个是该类本身,第二个是异常对象。

(6)on_close:在遇到连接关闭的情况时调用,参数只有一个,就是该类本身。

(7)on_cont_message:这个对象在接收到连续帧数据时被调用,有三个参数,分别是:类本身,从服务器接受的字符串(utf-8),连续标志。

(8)on_data:当从服务器接收到消息时被调用,有四个参数,分别是:该类本身,接收到的字符串(utf-8),数据类型,连续标志。

(9)keep_running:一个二进制的标志位,如果为True,这个app的主循环将持续运行,默认值为True。

(10)get_mask_key:用于产生一个掩码。

(11)subprotocols:一组可用的子协议,默认为空。

长连接关键方法:ws.run_forever(ping_interval=60,ping_timeout=5)

 如果不断开关闭websocket连接,会一直阻塞下去。另外这个函数带两个参数,如果传的话,启动心跳包发送。

ping_interval:自动发送“ping”命令,每个指定的时间(秒),如果设置为0,则不会自动发送。

ping_timeout:如果没有收到pong消息,则为超时(秒)。


ws.run_forever(ping_interval=60,ping_timeout=5)#ping_interval心跳发送间隔时间#ping_timeout 设置,发送ping到收到pong的超时时间

我们看源代码,会发现这样一断代码:

ping的超时时间,要大于ping间隔时间


   if not ping_timeout or ping_timeout <= 0:
     ping_timeout = None
   if ping_timeout and ping_interval and ping_interval <= ping_timeout:
     raise WebSocketException("Ensure ping_interval > ping_timeout")

长连接:

示例1:


import websocket
try:
 import thread
except ImportError:
 import _thread as thread
import time

def on_message(ws, message):
 print(message)

def on_error(ws, error):
 print(error)

def on_close(ws):
 print("### closed ###")

def on_open(ws):
 def run(*args):
   ws.send("hello1")
   time.sleep(1)
   ws.close()
 thread.start_new_thread(run,())

if __name__ == "__main__":
 websocket.enableTrace(True)
 ws = websocket.WebSocketApp("ws://echo.websocket.org/",
              on_message = on_message,
              on_error = on_error,
              on_close = on_close)
 ws.on_open = on_open
 ws.run_forever(ping_interval=60,ping_timeout=5)

示例2:


import websocket
from threading import Thread
import time
import sys

class MyApp(websocket.WebSocketApp):
 def on_message(self, message):
   print(message)

def on_error(self, error):
   print(error)

def on_close(self):
   print("### closed ###")

def on_open(self):
   def run(*args):
     for i in range(3):
       # send the message, then wait
       # so thread doesn't exit and socket
       # isn't closed
       self.send("Hello %d" % i)
       time.sleep(1)

time.sleep(1)
     self.close()
     print("Thread terminating...")

Thread(target=run).start()

if __name__ == "__main__":
 websocket.enableTrace(True)
 if len(sys.argv) < 2:
   host = "ws://echo.websocket.org/"
 else:
   host = sys.argv[1]
 ws = MyApp(host)
 ws.run_forever()

短连接:


from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()

来源:https://www.cnblogs.com/yhleng/p/9487764.html

标签:Python,WebSocket,长连接,心跳,短连接
0
投稿

猜你喜欢

  • python 教程实现 turtle海龟绘图

    2022-03-19 10:45:35
  • jQuery性能优化指南[译]

    2009-05-12 11:54:00
  • 通过代码实例了解Python异常本质

    2023-06-14 06:29:19
  • Go语言二进制文件的读写操作

    2023-06-23 09:40:08
  • Python+matplotlib实现堆叠图的绘制

    2023-07-21 17:38:35
  • 基于prototype扩展的JavaScript常用函数库

    2023-08-24 15:09:57
  • CSS+asp仿迅雷人气指数

    2009-08-03 14:11:00
  • Windows 下更改 jupyterlab 默认启动位置的教程详解

    2023-06-11 13:10:12
  • css彩色虚线表格及JS鼠标指向单元格变色制作方法

    2007-08-10 13:08:00
  • 如何让WML页面自己更新?

    2008-05-21 13:35:00
  • centos7利用yum安装lnmp的教程(linux+nginx+php7.1+mysql5.7)

    2023-11-14 11:40:18
  • PHP二维码的生成与识别案例

    2023-06-14 06:48:55
  • innerHTML 的一些问题

    2008-06-17 17:39:00
  • 通过索引优化含ORDER BY的MySQL语句

    2010-03-13 12:20:00
  • 一文带你掌握Python中文词频统计

    2022-11-17 21:02:00
  • 这么多的 Oracle 性能工具

    2008-06-04 11:20:00
  • Linux ORCLE数据库增量备份脚本

    2009-11-21 09:43:00
  • 浅谈php自定义错误日志

    2023-11-14 10:59:40
  • Python seaborn barplot画图案例

    2023-11-07 00:50:55
  • 如何判断用户是否非正常离开聊天室?

    2010-01-18 20:30:00
  • asp之家 网络编程 m.aspxhome.com