0
votes

I have a problem with an HTTPS and a WebSocket connection (I use Node.JS as a server). I have generated SSL certificates with OpenSSL and I imported them to the server with the following code:

const https = require('https');
var app = express();
...
const WebSocket = require('ws');
...
var serverHttps = https.createServer({
        key: fs.readFileSync(path.join(pathCertificati, 'key.pem')),
        cert: fs.readFileSync(path.join(pathCertificati, 'cert.pem'))
    }, app).listen(3000, () => {
    console.log('In ascolto sulla porta 3000 HTTPS.')
    })

const wss = new WebSocket.Server({
    server: serverHttps, 
    adress: '192.168.12.40',
    port: 9000
});

With this code I should have a WebSocket handling an HTTPS connection, correct?

Client side, I have the following code:

socket = new WebSocket("wss://192.168.12.40:9000");
socket.onopen = function ()...
socket.onclose = function ()...
socket.onerror = function (error) {
        console.log("Errore nella connessione!");
        console.log(error);
    }

When I load the page using the address: https://192.168.12.40:3000 and the above code is executed, the error message appears:

WebSocketScript.js:26 WebSocket connection to 'wss://192.168.12.40:9000/' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR

Do you have any ideas to establish the WebSocket Connection on an HTTPS page? Thanks a lot.

1

1 Answers

0
votes

I have found the solution to the problem. The solution is:

Server-side code:

var serverHttps = https.createServer({
        key: fs.readFileSync(path.join(pathCertificati, 'key.pem')),
        cert: fs.readFileSync(path.join(pathCertificati, 'cert.pem'))

    }, app).listen(3000, () => {
        // Messaggio di attivazione del server in ascolto sulla porta 3000
        console.log('Listening ' + 3000 + ' HTTPS.');
    })

serverHttps.on('upgrade', function upgrade(request, socket, head) {
    const pathname = url.parse(request.url).pathname;

    if (pathname === "/") {
        wss.handleUpgrade(request, socket, head, function done(ws) {
            wss.emit('connection', ws, request);
        });
    }
});

// Create WebSocket
const wss = new WebSocket.Server({ noServer: true });

wss.on('error', function () {...}
wss.on('connection', function (ws) {...}

Client side:

socket = new WebSocket("wss://192.168.12.40:3000);

This is the same address used on the server side and it fire the event "serverHttps.on('upgrade'"

Thanks a log...