Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js:代理websockets到其他端口大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在端口80上运行的node.js中编写了http代理.我只需要将socket.io流量重定向到端口9090,将标准http流量重定向到8080上的Apache.这是我的代理代码

httpProxy = require('http-proxy');

httpProxy.createServer(function (req,res,proxy) {
    if (req.url.match(/socket.io/)) {
        proxy.proxyrequest(req,{
            host: 'localhost',port: 9090
        });
    } else {
        proxy.proxyrequest(req,port: 8080
        });
    }
}).listen(80);

一切正常,但io.socket回归到xhr-polling.

http://localhost/client.htm    - falls BACk to xhr-polling

file:///C:/.../client9090.htm  - still uses websocket

socket.io app在端口9090上运行,client.htm连接到80,client9090.htm直接连接到9090.

看起来像node-http-proxy使socket.io应用程序在xhr-polling模式下工作.
客户端是Chrome v.25

socket.io应用程序代码

var io = require('socket.io').listen(9090);

io.on('connection',function (socket) {

        socket.on('hi!',function (data) {
            console.log(data);
            socket.emit('news');
        });

        socket.on('ahoj',function (data) {
            console.log(data);
        });
    });

client.htm代码

<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
    var chat = io.connect('http://localhost')

    chat.on('connect',function () {
        chat.emit('hi!');
    });

    chat.on('news',function () {
        chat.emit('ahoj',{a:1,b:2});
    });
</script>

client9090.htm是相同的,但localhost被localhost:9090取代

正如我所说,everythig运行良好,唯一的问题是,node-http-proxy使得从websockets回退到xhr-polling.
有人可以帮忙吗?

解决方法

根据 https://npmjs.org/package/http-proxy,在向httpProxy.createServer()添加回调时,您必须手动代理“升级”事件,如下所示:

httpProxy = require('http-proxy');

// added `var server =` here
var server = httpProxy.createServer(function (req,port: 8080
        });
    }
}).listen(80);

// added upgrade listener section here:
server.on('upgrade',function (req,socket,head) {
    server.proxy.proxyWebSocketrequest(req,head);
});

但是,对于上面描述的用法,您甚至不需要回调函数 – 您可以轻松地执行以下操作:

httpProxy = require('http-proxy');

var options = {
  pathnameOnly: true,router: {
    '/wiki': '127.0.0.1:8001','/blog': '127.0.0.1:8002','/api':  '127.0.0.1:8003'
  }
}

var proxyServer = httpProxy.createServer(options);
proxyServer.listen(80);

大佬总结

以上是大佬教程为你收集整理的node.js:代理websockets到其他端口全部内容,希望文章能够帮你解决node.js:代理websockets到其他端口所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。