我的要求是,如果某些用户通过WS或WSS连接,他们可以彼此通信。现在,如果我为WSS运行节点服务器,那么它不能通过HTTP运行,如果为WS运行,那么它就不能通过HTTPS连接。
经过长时间的研究,我找到了这个解决方案并按我的要求为我工作。这是我的sever.js文件。
/**
Before running:
> npm install ws
Then:
> node server.js
> open http://localhost:8080 in the browser
*/
const http = require('http');
const fs = require('fs');
const ws = new require('ws');
//for wss
const https = require('https');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const wss = new ws.Server({noServer: true});
const clients = new Set();
function accept(req, res) {
if (req.url == '/ws' && req.headers.upgrade &&
req.headers.upgrade.toLowerCase() == 'websocket' &&
// can be Connection: keep-alive, Upgrade
req.headers.connection.match(/\bupgrade\b/i)) {
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
} else if (req.url == '/') { // index.html
fs.createReadStream('./index.html').pipe(res);
} else { // page not found
res.writeHead(404);
res.end();
}
}
function onSocketConnect(ws) {
clients.add(ws);
log(`new connection`);
ws.on('message', function(message) {
log(`message received: ${message}`);
message = message.slice(0, 500); // max message length will be 50
for(let client of clients) {
client.send(message);
}
});
ws.on('close', function() {
log(`connection closed`);
clients.delete(ws);
});
}
let log;
if (!module.parent) {
log = console.log;
// for wss
https.createServer(options,accept).listen(8443);
http.createServer(accept).listen(8080);
} else {
// to embed into javascript.info
log = function() {};
// log = console.log;
exports.accept = accept;
}
现在WS和WSS链接将从同一文件运行。对于WSS端口将是8443,对于WS 8080,其他链接将保持不变。对于WSS,这些是必需的
键:fs.readFileSync('key.pem'),
cert:fs.readFileSync('cert.pem')
这是生成这些文件的帮助
//如何从密钥和CRT文件中获取PEM文件
openssl rsa-通知DER-更新PEM-输入server.key-输出server.crt.pem
让我知道是否遇到任何问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句