How to run a websocket server on ws and wss at same time that they both communicate or sync data with each other? Or WSS on HTTP and WS on HTTPS?

早过忘川 提交于 2021-02-08 08:21:33

问题


My requirement is this that if some users connect through WS or WSS they can communicate with each other.Now if i run node server for WSS it does not run over HTTP and if run for WS then it does not Connect on HTTPS .Any solution?


回答1:


After a long research at last i find this solution and is working for me as i was requiring.This is my sever.js file.

/**
Before running:
> npm install ws
Then:
> node server.js
> open http://localhost:8080 in the browser
*/


const http = require('http');
const fs = require('fs');
const ws = new require('ws');

//for wss
const https = require('https');
const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};


const wss = new ws.Server({noServer: true});

const clients = new Set();

function accept(req, res) {
  
  if (req.url == '/ws' && req.headers.upgrade &&
      req.headers.upgrade.toLowerCase() == 'websocket' &&
      // can be Connection: keep-alive, Upgrade
      req.headers.connection.match(/\bupgrade\b/i)) {
    wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
  } else if (req.url == '/') { // index.html
    fs.createReadStream('./index.html').pipe(res);
  } else { // page not found
    res.writeHead(404);
    res.end();
  }
}

function onSocketConnect(ws) {
  clients.add(ws);
  log(`new connection`);

  ws.on('message', function(message) {
    log(`message received: ${message}`);

    message = message.slice(0, 500); // max message length will be 50

    for(let client of clients) {
      client.send(message);
    }
  });

  ws.on('close', function() {
    log(`connection closed`);
    clients.delete(ws);
  });
}

let log;
if (!module.parent) {
  log = console.log;

// for wss
  https.createServer(options,accept).listen(8443);

  http.createServer(accept).listen(8080);
} else {
  // to embed into javascript.info
  log = function() {};
  // log = console.log;
  exports.accept = accept;
}

Now WS and WSS links will run from same file.For WSS port will be 8443 and for WS 8080,Other link will remain same. For WSS these are required

key: fs.readFileSync('key.pem'),

cert: fs.readFileSync('cert.pem')

and here is help for generating these files

//how-to-get-pem-file-from-key-and-crt-files

How to get .pem file from .key and .crt files?

openssl rsa -inform DER -outform PEM -in server.key -out server.crt.pem

Let me know if facing any issue.



来源:https://stackoverflow.com/questions/60536397/how-to-run-a-websocket-server-on-ws-and-wss-at-same-time-that-they-both-communic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!