连接状态恢复
¥Connection state recovery
首先,让我们假装没有断开连接来处理断开连接:此功能称为 "连接状态恢复"。
¥First, let's handle disconnections by pretending that there was no disconnection: this feature is called "Connection state recovery".
此功能将临时存储服务器发送的所有事件,并在客户端重新连接时尝试恢复客户端的状态:
¥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:
恢复其房间
¥restore its rooms
发送任何遗漏的事件
¥send any missed events
必须在服务器端启用它:
¥It must be enabled on the server side:
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.
添加 "断开" 按钮是出于演示目的。
¥The "Disconnect" button was added for demonstration purposes.
Code
- ES6
- ES5
<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>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
<button id="toggle-btn">Disconnect</button>
</form>
<script>
var toggleButton = document.getElementById('toggle-btn');
toggleButton.addEventListener('click', function(e) {
e.preventDefault();
if (socket.connected) {
toggleButton.innerText = 'Connect';
socket.disconnect();
} else {
toggleButton.innerText = 'Disconnect';
socket.connect();
}
});
</script>
很棒的!现在,你可能会问:
¥Great! Now, you may ask:
但这是一个很棒的功能,为什么默认情况下不启用它?
¥But this is an awesome feature, why isn't this enabled by default?
有几个原因:
¥There are several reasons for this:
它并不总是有效,例如,如果服务器突然崩溃或重新启动,则可能无法保存客户端状态
¥it doesn't always work, for example if the server abruptly crashes or gets restarted, then the client state might not be saved
扩展时并不总是可以启用此功能
¥it is not always possible to enable this feature when scaling up
话虽如此,这确实是一个很棒的功能,因为你不必在临时断开连接后(例如,当用户从 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.
- CommonJS
- ES modules