title: Https server with websockets on node.js
body: <p>I'm trying to create simple https server with websockets support. I had some functional code for https server and websockets, but both standalone. Don't know how to combine it. I prefer to use free to use libraries (MIT,..)</p>
  
  <p>I want to be able to serve http request and also websockets.</p>
  
  <p>Https example with upgrade, but don't know how to handle upgraded websocket connection as my second example bellow this.</p>
  
  <pre><code>connection. process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  
  var https = require('https');
  var websocket = require('websocket');
  var fs = require('fs');
  
  var options = {
      key:fs.readFileSync('./cert/server.key'),
      cert:fs.readFileSync('./cert/server.crt')
  };
  
  var server = https.createServer(
      options
    , function(req,res) {
  
      console.log('req');
  
      res.writeHeader(200, { 'Content-Type': 'text/plain' });
      res.write('test');
      res.end();
    }
  );
  server.on('upgrade', (req, socket, head) =&gt; {
  
      console.log('upgrade ');
  
    socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
                 'Upgrade: WebSocket\r\n' +
                 'Connection: Upgrade\r\n' +
                 '\r\n');
  
    socket.pipe(socket);
  });
  
  server.listen(8080, '127.0.0.1', () =&gt; {
  
    // make a request
    const options = {
      port: 8080,
      hostname: '127.0.0.1',
      headers: {
        'Connection': 'Upgrade',
        'Upgrade': 'websocket'
      }
    };
  
    const req = https.request(options);
    req.end();
  
    req.on('upgrade', (res, socket, upgradeHead) =&gt; {
  
      console.log('got upgraded!');
  
  *** so what to do here ***
  
  
      /*
      socket.end();
      process.exit(0);
      */
    });
  });
  </code></pre>
  
  <p>This is functional websockets but without possibility to handle simple http(s) requests.</p>
  
  <pre><code>var https = require('https');
  var ws = require('websocket').server;
  var fs = require('fs');
  
  var options = {
      key:fs.readFileSync('./cert/server.key'),
      cert:fs.readFileSync('./cert/server.crt')
  };
  
  
  var server = https.createServer(
          options
  , function(req,res) {
          res.writeHeader(200);
          res.end();
  }
  );
  
  server.listen(8080);
  
  
  var wss = new ws({httpServer:server});
  
  var connectionNumber=0;
  console.log('start ');
  wss.on('request',function(req){
  
          req.on('requestAccepted',function(conn){
  
                  conn.on('message',function(msg){
  
                          conn.send('test');
                  });
  
                  conn.on('close',function(msg){
                  });
  
          });
  
          req.accept(null,req.origin);
  });
  </code></pre>
  
  <p>I was looking for functional example of combined solution but haven't any luck.</p>