我建议使用websocket 包,它是一个
实现 RFC 6455 中指定的 WebSocket 协议的 Websocket 客户端和服务器库。
这就是我想要的,所以这就是我使用它的原因。使用起来非常轻松,我实际上是在使用纯 javascript websockets 从 html 客户端到 node.js 的 wss 和 ws 连接。
git 项目处于活动状态,当我发布问题时,我在同一天得到了回复。上面链接中的一个示例显示了它是多么简单:
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
但是,我应该指出,子协议并不明显,因为没有示例。不过,该项目的 git 站点上有一些问题可以引导您朝着正确的方向前进。