如何使websockets通过node.js中的代理

San*_*ero 6 javascript proxy push-notification websocket node.js

概括那将是一个问题......如何让websockets通过node.js中的代理?

在我的特定情况下,我正在使用pusher.com和他们推荐的node.js客户端库.查看代码内部我想知道一些关于我应该更改的提示,以使这个库与代理一起工作...你可以在这里查看代码

也许我应该以某种方式替换或修改库使用的websockets模块

编辑

谢谢你的回答/评论!需要考虑的几件事(对不起,如果我对其中的一些/全部错了,只是学习):

  • 我不想创建代理服务器.我只是想在公司内部使用现有的代理服务器来代理我的websockets请求(特别是pusher.com)
  • 只是为了让你知道,如果我使用像Windows Proxifier那样的接收器,我设置规则来检查所有到端口443的连接,以通过代理服务器proxy-my.coporate.com:1080(类型SOCKS5)它就像一个魅力.
  • 但我不想这样走.我想在我的节点js代码中以编程方式配置此代理服务器(即使涉及修改我提到的推送器库)
  • 我知道如何使用Request模块为HTTP执行此操作(查找提及如何使用代理的部分).
    • 我想要一个类似于websockets的东西.

You*_*Bet 10

来自 https://www.npmjs.com/package/https-proxy-agent

var url = require('url');
var WebSocket = require('ws');
var HttpsProxyAgent = require('https-proxy-agent');

// HTTP/HTTPS proxy to connect to
var proxy = process.env.http_proxy || 'http://168.63.76.32:3128';
console.log('using proxy server %j', proxy);

// WebSocket endpoint for the proxy to connect to
var endpoint = process.argv[2] || 'ws://echo.websocket.org';
var parsed = url.parse(endpoint);
console.log('attempting to connect to WebSocket %j', endpoint);

// create an instance of the `HttpsProxyAgent` class with the proxy server information
var options = url.parse(proxy);

var agent = new HttpsProxyAgent(options);

// finally, initiate the WebSocket connection
var socket = new WebSocket(endpoint, { agent: agent });

socket.on('open', function () {
  console.log('"open" event!');
  socket.send('hello world');
});

socket.on('message', function (data, flags) {
  console.log('"message" event! %j %j', data, flags);
  socket.close();
});
Run Code Online (Sandbox Code Playgroud)


The*_*ony 2

尝试节点http代理

它允许您通过代理发送 http 或 websocket 请求。

var http = require('http'),  
httpProxy = require('http-proxy');
//
// Create a basic proxy server in one line of code...
//
// This listens on port 8000 for incoming HTTP requests 
// and proxies them to port 9000
httpProxy.createServer(9000, 'localhost').listen(8000);

//
// ...and a simple http server to show us our request back.
//
http.createServer(function (req, res) {  
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);
Run Code Online (Sandbox Code Playgroud)

来源:链接

  • 我不认为这回答了问题......这只是增加了一个额外的中间人。它没有显示如何通过代理连接到远程 ws 端点。OP - 你找到解决方案了吗? (4认同)
  • 事实上,这“实现”了一个代理,并且没有解释如何通过代理打开套接字。你能指出我缺少的东西吗? (3认同)