简体   繁体   English

如何在NodeJS中将WebSocket连接代理到其他WebSocket

[英]How to proxy websocket connections to other websockets in NodeJS

I need to create a small authentication layer on top of a 3rd party web-socket based chat application. 我需要在基于第三方网络套接字的聊天应用程序之上创建一个小的身份验证层。 I have a simple API (get) that can validate api tokens from requests. 我有一个简单的API(获取),可以验证请求中的api令牌。 What I want to do is essentially validate their token (which I know how to do) then proxy the websocket connection to the actual chat server. 我要做的基本上是验证他们的令牌(我知道该怎么做),然后将websocket连接代理到实际的聊天服务器。

I've been looking for solutions and this thread seems to give some pointers in the right direction however I can't get any of the solutions to work. 我一直在寻找解决方案,并且该线程似乎在正确的方向上提供了一些指示,但是我无法获得任何有效的解决方案。

var http = require('http'),
    WebSocket = require('faye-websocket'),
    conf = require('./conf.json');

var server = http.createServer();

server.on('upgrade', function(request, socket, body) {
  console.log('upgrade fired');
  var frontend = new WebSocket(request, socket, body),
      backend  = new WebSocket.Client('ws://echo.websocket.org');

  frontend.pipe(backend).pipe(frontend);
});




server.on('connection', function(socket) {
  console.log('connection')
  backend = new WebSocket.Client('ws://echo.websocket.org');
  console.log(backend);
  socket.pipe(backend).pipe(socket);
})



server.listen(conf.port);
console.log('Listening on '+port.conf);

The connection event is fired, however the upgrade event which is supposed to be fired on a ws connection never is. 触发了连接事件,但是从来没有触发应该在ws连接上触发的升级事件。

The goal is to first authenticate a api key to an external server, then open a proxy to the chat websocket all through a request to this node server via a websocket connection. 目的是首先通过外部服务器对api密钥进行身份验证,然后通过通过websocket连接向该节点服务器发出的请求来打开所有聊天websocket的代理。 I'll most likely pass the api key as a get parameter for simplicity. 为了简单起见,我很可能将api键作为get参数传递。 I also looked at this package and attempted using it however it didn't work as well. 我也查看了这个程序包并尝试使用它,但是效果不佳。

The issue ended up being with nginx. 问题最终出在nginx身上。 I forgot I was proxying requests through the reverse proxy and by default nginx does not support the ws:// connection so it drops it. 我忘记了我是通过反向代理来代理请求的,默认情况下nginx不支持ws://连接,因此将其丢弃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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