Node.js: HTTPS 'websocket' upgrade returns a socket which is missing the .send(…args) method, why? – Server Fault

My server requests a websocket upgrade when a client connects, like:

const options = {
    port: 443,
    host: '0.0.0.0',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket',
    },
  };

  const req = http.request(options);
  req.end();

  req.on('upgrade', (res, socket, upgradeHead) => {
    console.log('got upgraded to:', socket, upgradeHead);
    socket.end();
  });

However, when I log the socket object to the console, it’s missing the send() method (which would send blobs, buffers or JSON). I guess there’s a difference between a Socket and a WebSocket. But then, how do I send data using this Socket (in the same manner that WebSocket.send(…args) would) or transform it to a WebSocket? (I prefer not to import the Node.js ‘ws’ module since it’s annoyingly complicated using GitHub.)

There is also an alternative solution: to launch the connection from the client using WebSocket API, like this:

const ws = new WebSocket('yourdomain.com');

However, in that case, I would still need to listen for the upgrade at the server and I don’t know how. When using a WS Server, you simply grab every WebSocket connection like

server.on('connection', ws=>{

// ws is the WebSocket object with .send() method
});

But using an HTTP server, it would probably be something like

HTTPserver.on('upgrade', (res, ws, upgradeHead)=>{ 

// ws is the WebSocket with send() method


 });

What’s the simplest solution?
Thanks!

Read more here: Source link