WebSocket - Tornado - Ping & Pong

目录

一、Tornado 内置 ping 设置

1-0 ping 帧

1-1 ping 帧 发送

1-2 Tornado setting 相关项

1-3 client & server 端处理 ping 帧

1-3-1 server 端

1-3-2 client 端 - 基于 ws-client 库

二、业务逻辑 ping & pong

2-0 业务逻辑分析

2-1 gzip 压缩

2-1-1 内置 gzip 相关 settings

2-1-2 手动 gzip 压缩 - 及 binary 注意点

2-2 Ping & Pong

2-2-1 server 端

2-2-2 client 端 - ws-client库


一、Tornado 内置 ping 设置

1-0 ping 帧

# bytes to int
int.from_bytes(data[0], 'big')
​
# int to bytes
int.to_bytes('转义位数','单个int位数左大右小')
int.to_bytes(13,'big')

1-1 ping 帧 发送

# server 接收ping值的返回(client 自动返回)
class EchoWebSocket(WebSocketHandler):
    # Invoked when the response to a ping frame is received.
    def on_pong(self, data):
        print('pong:', data)
        # 默认第一个发送的ping帧为空
        if not data:
            # 主动发送13位时间戳
            byte_ping = round(time.time()*1000).to_bytes(13,'big')
            self.ping(byte_ping)

1-2 Tornado setting 相关项

官方 setting 配置文档

if __name__ == "__main__":
    application = Application([
        (r"/", EchoWebSocket),
        (r"/oplog", OplogHandler),
​
    ],
        # 间隔5秒发送一次ping帧,第一次发送为触发的5s后
        websocket_ping_interval=5,
        # 每次 ping 操作重置时间超时时间,若超时则断开连接,默认3次 ping 或 30s 断开
        websocket_ping_timeout=10
    )
    application.listen(8080)
    ioloop.IOLoop.current().start()

1-3 client & server 端处理 ping 帧

1-3-1 server 端

class EchoWebSocket(WebSocketHandler):
​
    def open(self):
        print("WebSocket opened")
        users.add(self)
​
    # Invoked when the a ping frame is received.
    def on_ping(self, data):
        print('ping:', data)
​
    # Invoked when the response to a ping frame is received.
    def on_pong(self, d
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值