Skip to main content
Version: 4.x

教程步骤 #6 - 连接状态恢复


连接状态恢复

首先,让我们假装没有断开连接来处理断开连接: 此功能称为 "连接状态恢复"。

英:First, let's handle disconnections by pretending that there was no disconnection: this feature is called "Connection state recovery".

此功能将 temporarily 存储服务器发送的所有事件,并在客户端重新连接时尝试恢复客户端的状态:

英:This feature will temporarily store all the events that are sent by the server and will try to restore the state of a client when it reconnects:

  • 恢复其房间
  • 发送任何遗漏的事件

必须在服务器端启用它:

英:It must be enabled on the server side:

index.js
const io = new Server(server, {
connectionStateRecovery: {}
});

让我们看看它的实际效果:

英:Let's see it in action:

/videos/tutorial/connection-state-recovery.mp4

正如你在上面的视频中看到的,重新建立连接时最终会传递 "realtime" 消息。

英:As you can see in the video above, the "realtime" message is eventually delivered when the connection is reestablished.

note

添加 "断开" 按钮是出于演示目的。

英:The "Disconnect" button was added for demonstration purposes.

代码
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
<button id="toggle-btn">Disconnect</button>
</form>

<script>
const toggleButton = document.getElementById('toggle-btn');

toggleButton.addEventListener('click', (e) => {
e.preventDefault();
if (socket.connected) {
toggleButton.innerText = 'Connect';
socket.disconnect();
} else {
toggleButton.innerText = 'Disconnect';
socket.connect();
}
});
</script>

很棒的! 现在,你可能会问:

英:Great! Now, you may ask:

但这是一个很棒的功能,为什么默认情况下不启用它?

有几个原因:

英:There are several reasons for this:

  • 它并不总是有效,例如,如果服务器突然崩溃或重新启动,则可能无法保存客户端状态
  • 扩展时并不总是可以启用此功能
tip

话虽如此,这确实是一个很棒的功能,因为你不必在临时断开连接后(例如,当用户从 WiFi 切换到 4G 时)同步客户端的状态。

英:That being said, it is indeed a great feature since you don't have to synchronize the state of the client after a temporary disconnection (for example, when the user switches from WiFi to 4G).

我们将在下一步探索更通用的解决方案。

英:We will explore a more general solution in the next step.

info

你可以直接在浏览器中运行此示例:

英:You can run this example directly in your browser on: