您应该考虑迁移到socket.io
.
- 它具有内置的自动重新连接功能。而且您无需为此做任何事情。默认情况下已启用它。
- 令人惊讶的是,它与旧版浏览器兼容,甚至是不支持本机 websocket 的浏览器。
两者的代码非常相似,但socket.io
可能只是更短一点。例如,对于我们用来编写类似这样的服务器代码:
const WebSocketServer = require('websocket').server
const ws = new WebSocketServer({ httpServer });
ws.on('request', (request) => onConnection(request));
function onConnectionRequest(request) {
const connection = request.accept(null, request.origin);
if (!connection) return;
connection.on('message', (msg) => onMessageReceived(msg));
connection.on('close', () => onConnectionClosed());
}
function onMessage(message) {
if (message.type === 'utf8') {
const data = message.utf8Data;
const request = JSON.parse(data);
// todo use request
}
}
Socket.io 代码非常相似,只是更短一些。
const io = require('socket.io')(httpServer);
io.on('connection', (socket) => onConnection(socket));
function onConnection(socket) {
socket.on('message', (msg) => onMessage(msg));
socket.on('disconnect', (reason) => onDisconnect(reason));
}
function onMessage(request) {
// todo use request
}
但是,请记住,您还必须重写客户端代码。例如对于 Angular,我使用ngx-socket-io
插件,它极大地简化了代码。