简体   繁体   中英

Creating wss socket with ws npm library - error: socket hang up

Is there a way in which I can create and connect to a websocket server that has accepts wss rather than just ws in the path?

I am currently using the ws npm library to do something like:

const wss = new WebSocket.Server({port: 8080});

wss.on('connection', () => {
    console.log('connected!');
});

Then connecting in terminal:

wscat -c ws://localhost:8080

I would connect successfully and get the correct log message.

However I am wanting/needing to connect to a wss websocket, but cannot get this to work with the ws npm library.

wscat -c wss://localhost:8080

This returns the error: error: socket hang up

Is there some way around this at all?

You need to open a HTTPS server, in order to connect to it. This is also explained in the documentation of ws.

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

const server = https.createServer({
  cert: fs.readFileSync('/path/to/cert.pem'),
  key: fs.readFileSync('/path/to/key.pem')
});
const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

server.listen(8080);

WS with HTTPS

You can create certificates with Let's Encrypt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM