简体   繁体   中英

Proxying WebSockets through node-http-proxy doesn't work

These are the versions of node and required modules I am using:

  • Node.js: 0.10.16
  • Websocket Library: einaros/ws ws@0.4.28
  • Proxy server: nodejitsu/node-http-proxy http-proxy@0.10.3

When I run the following program my console output looks like this, and doesn't move beyond this point:

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

Here's the code:

// 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);

My problem eventually started when I was trying to use hipache, I then simplified things to node-http-proxy and then finally to this piece of code.

If you change the port the WebSocket client is connecting to from 9090 to 19000 (thereby bypassing the proxy), things seem to work fine.

Any suggestions, pointers, feedback would be greatly appreciated.

Thanks!

核心问题是node-http-proxy的主分支只与node <= 0.8.x兼容(参见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 ),但它不是主线分支,我没有发现任何何时合并和可用的迹象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM