工具函数
function buildHeaders(headers) {
const arr = [];
for (const [k, v] of Object.entries(headers)) {
arr.push(`${k}:${v}\r\n`)
}
return arr.join('');
}
function getHostAndPort(req) {
let host;
let port;
try {
[host, port] = new URL(req.url);
} catch(e) {
[host, port] = req.headers.host.split(':');
} finally {
if (!port) {
port = 80;
}
}
console.log(host, port);
return [host, port];
}
1 http代理
const server = http.createServer((req, res) => {
const [host, port] = getHostAndPort(req);
http.get({
port,
host,
path: req.url
}, (response) => {
response.pipe(res);
});
});
2 websocket代理
server.on('upgrade', (req, res, head) => {
const [host, port] = getHostAndPort(req);
const client = net.connect({
port,
host,
});
client.on('connect', () => {
client.write(`GET ${req.url}\r\n` + buildHeaders(req.headers) + '\r\n');
res.pipe(client);
client.pipe(res);
});
client.on('error', () => {
res.destroy();
})
});
3 https代理
server.on('connect', (req, client, head) => {
const [host, port] = getHostAndPort(req);
const socket = net.connect(port, host, () => {
client.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
socket.write(head);
socket.pipe(client);
client.pipe(socket);
});
});
最后写一个https服务器测试
var https = require('https');
var fs = require('fs');
const WebSocket = require('ws');
var options = {
key: fs.readFileSync('./files/server-key.pem'),
ca: [fs.readFileSync('./files/ca-cert.pem')],
cert: fs.readFileSync('./files/server-cert.pem')
};
const server = https.createServer(options,function(req,res){
res.end('ok');
}).listen(11111);
同样我们也可以写一个websocket服务器进行测试,写完后把浏览器的代理改成代理服务器的地址就可以了。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有