我正在使用龙卷风Web套接字,并想计算到客户端的Web套接字延迟。我见过在龙卷风中使用ping / pong,但是我不太清楚,也没有很好的例子。
有没有简单的示例代码来发送ping / pong响应并计算Web响应?
答案 0 :(得分:0)
我已使用以下代码计算WebSocket延迟。 Ping将发送一个时间戳。在Pong中,我们收到ping时间戳,并通过从当前时间中减去ping时间戳来计算延迟。
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
ping_errors = 0
# Send a ping packet with the timestamp
def send_ping():
global ping_errors
timestamp = time.time()
try:
self.ping(str(timestamp).encode('utf-8'))
ping_errors = 0
except tornado.websocket.WebSocketClosedError:
msg = "Web socket closed. Stopped ping."
logger.info(msg)
pinger.stop()
except Exception:
ping_errors += 1
msg = "Ping failed to send."
logger.error(msg, exc_info=True)
if ping_errors > 3:
msg = "Stopping ping."
logger.error(msg, exc_info=True)
pinger.stop()
interval = 10000 #ms
pinger = tornado.ioloop.PeriodicCallback(send_ping, interval)
pinger.start()
def on_pong(self, timestamp):
curr_time = time.time()
time_diff = curr_time - float(timestamp)
if time_diff < 0:
logger.info("Lost a ping packet")
return
logger.info("WebSocket Latency: {0}ms".format(
int(ceil(time_diff * 1000))))
def on_close(self):
print("WebSocket closed")
在处理程序中,
handlers = [
...,
(r'/ping', EchoWebSocket),
]
在javascript中,
protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
ping_ws_url = protocol + window.location.host + "/ping";
ping_ws = new WebSocket(ping_ws_url);