开发者

Advantage/disadvantage of using socketio heartbeats

开发者 https://www.devze.com 2023-03-27 22:04 出处:网络
Socket.io allows you to use heartbeats to \"check the health of Socket.IO connections.\" What exactly are heartbeats and why sho开发者_Go百科uld or shouldn\'t I use them?A heartbeat is a small message

Socket.io allows you to use heartbeats to "check the health of Socket.IO connections." What exactly are heartbeats and why sho开发者_Go百科uld 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.

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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号