Node.js使用websocket调用Http代理IP的代码样例

温馨提示:
1. 安装ws库:npm install ws
2. 安装https-proxy-agent库: npm install https-proxy-agent

参考样例

const WebSocket = require('ws');
// https-proxy-agent 6.0.0 及以上版本
const { HttpsProxyAgent } = require("https-proxy-agent");
// https-proxy-agent 6.0.0 以下版本
// const HttpsProxyAgent = require("https-proxy-agent");

// 代理ip和代理端口
let proxyIp = '159.138.141.125'
let proxyPort = 11916

// 配置用户名和密码
let username = 'username'
let password = 'password'

const target = 'ws://echo.websocket.events/';
const agent = new HttpsProxyAgent(`http://${username}:${password}@${proxyIp}:${proxyPort}`);
const socket = new WebSocket(target, {agent});

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

socket.on('message', function (data, flags) {
	console.log('"message" event!', data, flags);
	socket.close();
});