K
K
Konstantin Malyarov2019-07-22 13:05:06
Digital certificates
Konstantin Malyarov, 2019-07-22 13:05:06

How to pass WebSocket over SSL?

There is a server (taken from the official documentation).

const https = require('https');
const fs = require('fs');
const WebSocket = require('ws');

const server = https.createServer({
    cert: fs.readFileSync('webhook_cert.pem'),
    key: fs.readFileSync('webhook_pkey.pem')
});

const wss = new WebSocket.Server({server});

wss.on('connection', function connection(ws) {
    ws.on('message', function message(msg) {
        console.log(msg);
    });
});

server.listen(3000, function listening() {
    const ws = new WebSocket(`wss://localhost:${server.address().port}`, {
        rejectUnauthorized: false
    });

    ws.on('open', function open() {
        ws.send('All glory to WebSockets!');
    });
});

There is a client:
websocketClient: function () {
            const ws = new WebSocket('wss://site.ru:3000/')
            ws.onopen = () => console.log('ONLINE')
            ws.onclose = () => console.log('DISCONNECT')
            ws.onmessage = response => console.log(response.data)
        }

When connecting, an error pops up:

WebSocket connection to 'wss://localhost:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

How to properly configure WebSockets?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question