在谈到WebSockets时,似乎互联网上有很多ws://(不安全)的教程,但在wss://(安全)上几乎没有。多亏了Supun Kavinda's tutorial,我的Node.js的网络套接字连接不安全,但无法正常工作。
以下是不安全连接(假ip地址)的摘要工作代码:
文件:js-index.js
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://3.00.00.00:8080');
文件:server.js
const https = require('https');
const fs = require('fs');
var WebsocketServer = require('websocket').server;
var server = https.createServer(function(request,response) {
function getPostParams(request, callback) {
var qs = require('querystring');
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var POST = qs.parse(body);
callback(POST);
});
}
}
if (request.method === "POST") {
getPostParams(request, function(POST) {
messageClients(POST.data);
response.writeHead(200);
response.end();
});
return;
}
});
server.listen(8080);
/*Handling websocket requests*/
var websocketServer = new WebsocketServer({
httpServer: server
});
websocketServer.on("request", websocketRequest);
global.clients = {}; // connected clients
var connectionId = 0;
function websocketRequest(request) {
var connection = request.accept(null, request.origin);
connectionId++;
clients[connectionId] = connection;
}
function messageClients(message) {
for (var i in clients) {
clients[i].sendUTF(message);
}
}
对于安全连接,我已经尝试了很多方法,主要集中在将ws://更改为wss://,并在createServer()调用中包括.pem证书/密钥,如下所示:
const ssl_creds = {
cert: fs.readFileSync('/opt/bitnami/apache2/htdocs/fullchain.pem'),
key: fs.readFileSync('/opt/bitnami/apache2/htdocs/privkey.pem')
};
var server = https.createServer(ssl_creds, function(request,response) {....
但是,我继续遇到错误(到目前为止,仅在Chrome中进行测试),例如:
- 建立连接错误:net :: ERR_CERT_COMMON_NAME_INVALID
- WebSocket握手时出错:发送了非空的“ Sec-WebSocket-Protocol”标头,但未收到任何响应
^#1是我最常遇到的问题
我正在使用由LetsEncrypt为其网站本身授予的ssl凭据-我认为可以吗?
总而言之,我发现的大多数教程要么做完全一样的事情,要么谈论设置代理/隧道如何需要NGINX之类的东西-我完全一无所知。
有人可以告诉我是否通常需要为此进行代理配置,或者我只是缺少一些小/笨拙的东西?任何见解将不胜感激。如果相关的话,我只是用来自Bitnami的Lightsail PHP映像在AWS上cutting之以鼻。