Search code examples
websockethttpsserverclientws

Connect two node.js servers with websockets (ws package) (https)


I'm trying to connect two node.js servers via websocket using the ws package. Here is some code:

Client server:

var socket = new WebSocket("wss://localhost:9000");

socket.addEventListener('open', function (event) {
    console.log("websocket connected");
})

socket.addEventListener('message', function (event) {
    console.log("message from backend server: ", event.data);
})

Backend server:

var https = require('https');
    
var httpsServer = https.createServer(credentials, app);
    
const WebSocket = require('ws');

const wss = new WebSocket.Server({ server:httpsServer });
    
wss.on('connection', function (ws) {
  console.log("websocket connnected");
})
    
httpsServer.listen(9000, function () {
  console.log(`server started on port 9000 via https`);
});

When I run this code, a get an error message on the command prompt that says "Error: certificate has expired". I am using a self-signed ssl certificate, which works perfectly fine for a websocket between a node.js server and the browser so I'm not convinced there's anything wrong with the certificate. I've seen examples of how to make this work using socket.io and socket.io-client, but how can I make it work using the ws package?


Solution

  • This is a problem with the ssl certificate. For some reason, going from browser to node.js server using a self-signed ssl certificate is fine, but going from node.js server to node.js using a self-signed ssl certificate is not.

    I created a brand new ssl certificate and then in the client server, instead of:

    var socket = new WebSocket("wss://localhost:9000");
    

    .. I now have:

    var socket = new WebSocket("wss://localhost:9000", {
      rejectUnauthorized: false
    });
    

    ..and it works.