我在Web应用程序中使用WebSockets。在Chrome和Firefox中一切正常。在Edge浏览器中,经过一段时间不活动后,只会断开连接。并在控制台中显示消息:
websocket错误:网络错误12030,与服务器的连接是 异常终止。
对于应用程序而言,连接是永久性的。
以下是服务器和客户端的一部分:
服务器
var options = {
key: fs.readFileSync(path.join(__dirname, 'cert/server.key')),
cert: fs.readFileSync(path.join(__dirname, 'cert/server.crt'))
};
var server = https.createServer(options, app);
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
// Handle Socket Request
wsServer.on('request', function(request) {
try {
// Do Stuff
var connection = request.accept('echo-protocol', request.origin);
// Do Stuff
} catch(error) {
console.log('Error during socket request: ', error);
}
// Handle Socket message
connection.on('message', function(message) {
try {
// Do Stuff
} catch(error) {
console.log('Error while receiving message: ', error);
}
});
// Handle Socket disconnect
connection.on('close', function(reasonCode, description) {
try {
// Make sure to remove closed connections from the global pool
delete clients[connection.location][connection.id];
} catch(error) {
console.log('Error while disconnecting socket: ', error);
}
});
});
// start server, listen to port
server.listen(49152, function() {
console.log((new Date()) + ' Server is listening on port 49152');
});
客户端
// connecting to the web server
var socket = new WebSocket(socketProtocol + '://' + socketServer + '', 'echo-protocol');
// listening for server response
socket.onmessage = function (message) {
// Do Stuff
};
// listening for any socket error
socket.onerror = function (error) {
console.log('WebSocket error: ' + error);
};
// listening for connection to be open
socket.onopen = function (e) {
console.log('connected');
};
为什么会发生这种情况?
我已经考虑过使用socket.io和/或进行某种轮询,因此连接仍然存在。但我希望有一种方法可以让我不必改变一切。