我目前正在尝试在chrome和NodeJS服务器之间创建一个websocket。节点服务器正在使用ws插件,而我正在使用Chrome的默认Websocket处理程序。
这是我的服务器代码行:
wss.on('connection', function connection(ws) {
ws.id = uuid();
let response = {'type': 'uuid','data': ws.id};
ws.send(JSON.stringify(response));
});
以及我给客户的代码:
//Listens for new messages
connection.onmessage = function(e) {
let data = JSON.parse(e.data);
console.log(data.data);
}
我期望:每次创建连接时,服务器都会为客户端生成一个UUID,客户端会将其打印到控制台。当连接断开并且客户端重新连接时,服务器将向客户端发送新的UUID。
发生的情况:服务器在创建连接时为客户端生成UUID,客户端将其打印到控制台。但是,当服务器关闭并重新启动,并且客户端重新建立连接时,服务器会向客户端发送新的UUID,但是chrome不会接听。
任何帮助将不胜感激。谢谢!
编辑:这是我重新连接到服务器的方式
//Reconnect to server
setInterval(function() {
if (connection.readyState !== WebSocket.OPEN) {
reconnect = false;
connection.close();
console.log("Disconnected from server. Retrying...");
connection = new WebSocket(server);
} else {
if (!reconnect) {
reconnect = true;
console.log("Reconnected to server.");
}
}
}, 1000);
编辑2:修改了代码,仍然无法使用:
//Webhook
//On connection open
connection.onopen = function() {
console.log("Connected to server");
reconnect = "";
//Reconnect to server if disconnected
connection.onclose = function(e) {
console.log("Connection closed, reconnecting...");
//Retry every second
reconnect = setInterval(function() {
if (connection.readyState !== WebSocket.OPEN) {
connection.close();
console.log("Connecting to server...");
connection = new WebSocket(server);
}
}, 1000);
}
}
[onopen()
也不在重新连接上触发,因此客户端将在断开连接后每秒尝试重新连接,并且永远不会停止。
我找到了解决方案
//Webhook
function connect() {
//Attempt to connect to server
if (firstConnect) {
console.log("Connecting to server...");
connection = new WebSocket(server);
} else {
if (connection.readyState !== WebSocket.OPEN) {
connection.close();
console.log("Connecting to server...");
connection = new WebSocket(server);
}
}
//On connection open
connection.onopen = function() {
firstConnect = false;
console.log("Connected to server");
clearInterval(reconnect);
}
//Listens for new messages
connection.onmessage = function(e) {
}
//Reconnect to server if disconnected
connection.onclose = function(e) {
console.log("Connection closed, reconnecting...");
connect();
}
}
当您创建新的套接字连接时,chrome将反复尝试自行连接,直到超时为止。超时将触发connection.onclose
,依次调用connect()
。
通过将其全部嵌套在connect()
中,事件处理程序将每次都挂接到新的websocket连接上。此外,您不需要setInterval()
,从而避免了任何性能问题。
浏览器在以下设备上测试:Chrome,Opera,Safari