如何将websocket连接(Node.js + ws)从端口A转发到端口B?

时间:2018-02-05 11:08:51

标签: node.js

如果我的服务器运行在8000端口,请说:

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

然后我希望将端口8000上收到的消息转发到端口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();
    }
  });
});

可悲的是,这种实施似乎并不奏效。什么是正确的方法呢?

1 个答案:

答案 0 :(得分:3)

  

这样做的正确方法是什么?

我会使用node-http-proxy,这将抽象出代理ws请求的细节:

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);
});
相关问题