Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward websocket connection (Node.js + ws) from port A to port B?

Tags:

node.js

Let's say if I have a server running at 8000 port like this:

  var s = http.createServer();
  s.on('request', function(request, response) {
    response.writeHeader(200);
    response.end();
  });
  s.listen(8000);
  var w = new WebSocketServer({
    server: s
  });

And then I wish to forward the message received on port 8000 to port 9000:

w.on('connection', function(ws) {
  var remote = null;

  ws.on('message', function(data) {
    remote = new WebSocket('ws://127.0.0.1:9000');
    remote.on('open', function() {
      remote.send(data);
    });
  });
  ws.on('close', function() {
    if (remote) {
      return remote.destroy();
    }
  });
  return ws.on('error', function() {
    if (remote) {
      return remote.destroy();
    }
  });
});

Sadly this implementation doesn't seem to work. What would be the right way to do this?

like image 850
Aero Wang Avatar asked Feb 05 '18 11:02

Aero Wang


1 Answers

What would be the right way to do this?

I would use node-http-proxy, which would abstract away the details of proxying the ws requests:

var proxy = new httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 9000
  }
});

s.on('request', function(request, response) {
     proxy.web(request, response);
  });

s.on('upgrade', function (req, socket, head) {
     proxy.ws(req, socket, head);
});
like image 77
Daniel Conde Marin Avatar answered Oct 02 '22 15:10

Daniel Conde Marin