ws: ws on ssl not working

I run this in the server side. The client can’t connect and it doesn’t shows errors.

var cfg = {

 ssl: true,
 port: 8080,
 ssl_key: 'cert.key',
 ssl_cert: 'cert.crt'

};

var httpServ = ( cfg.ssl ) ? require(‘https’) : require(‘http’);

var WebSocketServer = require(‘ws’).Server;

var app = null;

// dummy request processing var processRequest = function( req, res ) {

res.writeHead(200);
res.end("All glory to WebSockets!\n");                  

};

if ( cfg.ssl ) {

 app = httpServ.createServer({

      // providing server with  SSL key/cert
      key: fs.readFileSync( cfg.ssl_key ),
      cert: fs.readFileSync( cfg.ssl_cert ),
      passphrase: '1234',
      requestCert: true,
      rejectUnauthorized: false,

      }, processRequest ).listen( cfg.port );

} else { app = httpServ.createServer( processRequest ).listen( cfg.port ); }

var wss = new WebSocketServer( { server: app } );

wss.on(‘connection’, function(ws) { console.log(“Connected!”); ws.on(‘message’, function(message) { console.log(‘received: %s’, message); }); ws.send(‘something’); });


In the client side, I use: socket = new WebSocket(“wss://192.168.1.34:8080”);

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 16 (1 by maintainers)

Most upvoted comments

@chovy Any suggestions on connecting to a server (that uses a self-signed cert) from another server? (eg: another NodeJS process)

var WebSocket = require('ws');

var ws = new WebSocket('wss://192.x.x.x:4443', '', {
  headers: {token: 'xxxxxx'}
});

I can connect to my server from Google Chrome, but not from the terminal.

Error: unable to verify the first certificate

EDIT: Figured out how to allow self-signed certs (never use this in production):

// Do this before calling `new WebSocket` on the client server (not the websocket server).
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;

I got it working, I wrote about it here for anyone interested: http://www.chovy.com/web-development/self-signed-certs-with-secure-websockets-in-node-js/

@aleclarson You can also use the rejectUnauthorized option when creating the client instead of using the env variable.

Closing this as it seems everything has been addressed/solved.