WebSocket断线重连问题分析与代码实现
问题现象:在Web Session设置为30分钟超时的场景下,如果用户在有效期内未主动退出系统,但WebSocket连接因网络波动等原因意外中断,此时用户若想进行聊天或其他基于WebSocket的操作,必须手动重新建立连接。
具体实现代码如下所示:
var socket;
var $ = function() {
return document.getElementById(arguments[0]);
}
var log = function(msg) {
$("log").innerHTML ? $("log").innerHTML += "
" + msg : $("log").innerHTML = msg;
}
var initWebSocket = function() {
if (window.WebSocket) {
socket = new WebSocket("ws://127.0.0.1:8080/websocket");
socket.onmessage = function(event) {
var json = JSON.parse(event.data);
document.getElementById("message").value = json.message;
};
socket.onopen = function(event) {
log("Web Socket opened!");
};
socket.onclose = function(event) {
log("Web Socket closed.");
};
socket.onerror = function(event) {
log("Web Socket error.");
};
} else {
log("Your browser does not support Web Socket.");
}
}
var send = function() {
var data = function() {
socket.send("{'send':1,'take':2,'message':" + Math.random() + "}");
};
if (socket.readyState !== 1) {
socket.close();
initWebSocket();
setTimeout(function() {
data();
}, 250);
} else {
data();
};
}
window.onload = function() {
initWebSocket();
}
上述内容即为解决Spring WebSocket因自动断开及重连所引发问题的完整方案,希望能为读者提供参考与帮助,同时也欢迎支持本站。