Python_WebSocket长连接心跳与短连接方法

一、安装websocket-client

1、安装

pip install websocket-client

二、方法

1、我们先看一下,长连接调用方法:

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()

2、长连接,参数介绍:

(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的超时时间
  • 长连接方法:
import websocket
import json
import time
try:
    import thread
except ImportError:
    import _thread as thread


def on_message(ws, message):
    '''服务器有数据更新时,主动推送过来的数据'''
    print(message)


def on_error(ws, error):
    '''程序报错时,就会触发on_error事件'''
    print(error)


def on_close(ws):
    '''关闭websocket连接后,打印此消息'''
    print("### closed ###")


def on_open(ws):
    '''连接到服务器之后就会触发on_open事件,这里用于send数据'''
    def run(*args):
        Sign = {
            "name": 1,
            "nam2": 2
            }
        ws.send(json.dumps(Sign))  # 发送数据(必须为str类型)
        time.sleep(1)
        ws.close()  # 关闭连接
    thread.start_new_thread(run, ())


def run_1():
    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_timeout=5)
    # ws.run_forever()


if __name__ == "__main__":
    run_1()

  • 短连接方法(使用create_connection链接,此方法不建议使用,链接不稳定,容易断,并且连接很耗时):
import time
import json
from websocket import create_connection


class webcket:
    def __init__(self):
        self.url = "ws://echo.websocket.org/"

    def connect(self):
        '''一直链接,直到连接上就退出循环'''
        while True:
            try:
                self.ws = create_connection(self.url)
                print(self.ws)
                break
            except Exception as e:
                print('连接异常:', e)
                continue

    def send_data(self):
        '''连接成功后,发送数据'''
        Sign = {
            "name": 1,
            "nam2": 2
            }
        self.ws.send(json.dumps(Sign))  # 发送数据(必须为str类型)

    def run(self):
        '''执行,然后循环获取服务器返回的数据'''
        self.connect()
        self.send_data()
        time.sleep(1)
        while True:
            response = self.ws.recv()
            print(f"结果:{response}")


if __name__ == '__main__':
    webcket().run()
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值