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
猜你喜欢
- 和单选框一样,许多新手在用 Javascript 验证表单(form)中多选框(checkbox)的值时,都会遇到问题,原因是 checkb
- 目录前言super的用法super的原理Python super()使用注意事项混用super与显式类调用不同种类的参数总结前言Python
- 一个不错的js星级评分代码,可以评多个指标。相关文章推荐:用css制作星级投票评分功能 效果图:<script language=&q
- ORA-01578:Oracle data block corrupted(file # num,block # num)产生原
- 本文介绍了prototype.js常用函数及其使用方法例子说明函数名
- Go微服务网关从核心原理理解网关的本质网关具备的基本功能:支持多种协议代理:tcp/http/ websocket/grpc支持多种负载均衡
- 【名称】Abs【类别】数学函数【原形】Abs(number)【参数】必选的。Number参数是一个任何有效的数值型表达式【返回值】同numb
- 代码如下:title=request("title") title=replace(title,"chr(3
- XML被设计用来描述数据,其焦点是数据的内容。HTML被设计用来显示数据,其焦点是数据的外观。  
- 大家都熟悉迅雷看看里面的电影人气指数这个小图标吧先看看我的效果图再看看迅雷的截图比较好看,是根据电影的人气指数来显示热度,下面我们就来模仿一
- 说下防止PHPDDOS发包的方法 if (eregi("ddos-udp",$read)) { fputs($verbi
- 一、实验目的(1)熟练使用Counter类进行统计(2)掌握pandas中的cut方法进行分类(3)掌握matplotlib第三方库,能熟练
- 这可是个综合性的问题,看看下面对文件操作的集大成代码:<% 'Set file i/
- 本文实例讲述了JS实现运动缓冲效果的封装函数。分享给大家供大家参考,具体如下:之前经常写运动函数,要写好多好多,后来想办法封装起来。(运动缓
- asp压缩access数据库,具体asp代码见下: Class DatabaseTools &n
- 先上个效果图,就是用左右尖括号可改变中间日期的值。(点击中间显示区域有时间选择器弹框,用的插件就不说了,主要说自己原创的部分) &
- 最近接触到Tencent的广告越来越多,户外广告牌和电视上都是,可以明显感觉到Tencent的扩张野心,以及对QQ品牌定位的重塑。摆脱低龄化
- 什么是存储过程呢?定义:将常用的或很复杂的工作,预先用SQL语句写好并用一个指定的名称存储起来, 那么以后要叫数据库提供与已定义好的存储过程
- 下面是BeforeInitialBind事件过程:<SCRIPT language=vbscript event=
- 双屏不是什么新鲜事,不过相信国内前端工程师还是用单屏的多,前端开发需要同时开启的屏幕太多了…你有没有迷失windows任务栏下n个窗口和AL