【问题标题】:Proxying WebSockets through node-http-proxy doesn't work通过 node-http-proxy 代理 WebSocket 不起作用
【发布时间】:2013-08-18 00:25:56
【问题描述】:

这些是我正在使用的节点版本和所需模块:

  • Node.js:0.10.16
  • Websocket 库:einaros/ws ws@0.4.28
  • 代理服务器:nodejitsu/node-http-proxy http-proxy@0.10.3

当我运行以下程序时,我的控制台输出如下所示,并且不会超出这一点:

$ node app.js
proxy: got upgrade, proxying web request
wss: got connection

代码如下:

// app.js
// A simple proxying example
//
// Setup websocket server on port 19000
// Setup proxy on port 9000 to proxy to 19000
// Make a websocket request to 9000
//

var WebSocket = require('ws'),
    WebSocketServer = WebSocket.Server,
    proxy = require('http-proxy');

// goes in a loop sending messages to the server as soon as
// the servers are setup
var triggerClient = function() {
    var ws = new WebSocket('ws://localhost:9090/');
    ws.on('open', function() {
        console.log('ws: connection open');
        setInterval(function() {
            ws.send("Hello");
        }, 1000);
    });

    ws.on('message', function(data) {
        console.log('ws: got ' + data);
    });
}

// setup websocket server and a proxy
//
var go = function() {
    // setup a websocket server on port 19000
    //
    var wss = new WebSocketServer({ port: 19000 });
    wss.on('connection', function(ws) {
        console.log('wss: got connection');
        ws.on('message', function(data) {
            console.log('wss: got ' + data);
            ws.send('wss response: ' + data);
        });
    });


    // setup a proxy server
    var server = proxy.createServer(function (req, res, proxy) {
        proxy.proxyRequest(req, res, {
            host: 'localhost',
            port: 19000
        });
    });

    server.on('upgrade', function (req, socket, head) {
        console.log('proxy: got upgrade, proxying web request');
        server.proxy.proxyWebSocketRequest(req, socket, head, {
            host: 'localhost',
            port: 19000
        });
    });

    server.listen(9090, triggerClient);
};

process.nextTick(go);

当我尝试使用 hipache 时,我的问题最终开始了,然后我将事情简化为 node-http-proxy,最后简化为这段代码。

如果您将 WebSocket 客户端连接的端口从 9090 更改为 19000(从而绕过代理),一切似乎都可以正常工作。

任何建议、指点、反馈将不胜感激。

谢谢!

【问题讨论】:

标签: node.js websocket http-proxy node-http-proxy


【解决方案1】:

核心问题是node-http-proxy的master分支只兼容node https://github.com/nodejitsu/node-http-proxy#when-to-use-node-http-proxy):有一个树实现了对0.10.x的支持(见https://github.com/nodejitsu/node-http-proxy/tree/caronte)但它不是主线分支,我还没有找到任何迹象表明它何时会被合并并可用。

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2014-03-04
    • 2016-09-09
    相关资源
    最近更新 更多