使用socketio心跳的优缺点 [英] Advantage/disadvantage of using socketio heartbeats

查看:70
本文介绍了使用socketio心跳的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Socket.io 允许您使用心跳来检查 Socket.IO 连接的健康状况".心跳究竟是什么,我为什么应该或不应该使用它们?

Socket.io allows you to use heartbeats to "check the health of Socket.IO connections." What exactly are heartbeats and why should or shouldn't I use them?

推荐答案

心跳是从客户端发送到服务器(或从服务器到客户端再返回到服务器)的小消息,以定期间隔发送,以确认客户端仍然存在且活跃.

A heartbeat is a small message sent from a client to a server (or from a server to a client and back to the server) at periodic intervals to confirm that the client is still around and active.

例如,如果您有一个为聊天室服务的 Node.js 应用程序,并且用户在几分钟内没有说话,则无法判断他们是否真的仍然保持联系.通过以预定间隔(例如,每 15 秒)发送一次心跳,客户端通知服务器它仍然存在.如果它已经例如服务器从客户端收到心跳 20 秒后,很可能已断开连接.

For example, if you have a Node.js app serving a chat room, and a user doesn't say anything for many minutes, there's no way to tell if they're really still connected. By sending a hearbeat at a predetermined interval (say, every 15 seconds), the client informs the server that it's still there. If it's been e.g. 20 seconds since the server's gotten a heartbeat from a client, it's likely been disconnected.

这是必要的,因为您无法保证通过 TCP 干净地终止连接--如果客户端崩溃或发生其他事情,您将不会收到来自客户端的终止数据包,并且服务器不会知道客户端已断开连接.此外,Socket.IO 支持各种其他机制(TCP 套接字除外)来传输数据,在这些情况下,客户端不会(或不能)向服务器发送终止消息.

This is necessary because you cannot be guaranteed a clean connection termination over TCP--if a client crashes, or something else happens, you won't receive the termination packets from the client, and the server won't know that the client has disconnected. Furthermore, Socket.IO supports various other mechanisms (other than TCP sockets) to transfer data, and in these cases the client won't (or can't) send a termination message to the server.

默认情况下,Socket.IO 客户端会每 15 秒(心跳间隔)向服务器发送一次心跳,如果服务器在 20 秒内没有收到客户端的消息(心跳超时)会认为客户端断开连接.

By default, a Socket.IO client will send a heartbeat to the server every 15 seconds (heartbeat interval), and if the server hasn't heard from the client in 20 seconds (heartbeat timeout) it will consider the client disconnected.

我想不出很多您可能不想使用心跳的普通用例.

I can't think of many average use cases where you probably wouldn't want to use heartbeats.

这篇关于使用socketio心跳的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆