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?
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);
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With