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

Aer*_*ang 5 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
  });
Run Code Online (Sandbox Code Playgroud)

然后我希望将在端口 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();
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

可悲的是,这个实现似乎不起作用。这样做的正确方法是什么?

Dan*_*rin 5

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

我会使用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);
});
Run Code Online (Sandbox Code Playgroud)