nodejs 简单的模拟代理服务器
2021-02-02 23:15
标签:address href nts create let tostring res server 请求 代理前:client -> server 代理后:client -> proxy -> server game-client.js: game-server.js: game-proxy-server.js client print: prixy print: nodejs 简单的模拟代理服务器 标签:address href nts create let tostring res server 请求 原文地址:https://www.cnblogs.com/ajanuw/p/13163184.html
const net = require("net");
const serverAddress = {
host: "127.0.0.1",
port: 5000,
};
const proxyAddress = {
host: "127.0.0.1",
port: 3000,
};
let a = 0;
// 这里要处理的就是,如何把client请求地址,指向我编写的代理服务器
const client = net.createConnection(/* serverAddress */proxyAddress, () => {
console.log("client start port is: " + client.address().port);
setInterval(() => {
console.log(`--> ${a}`);
client.write(a.toString());
a++;
}, 1000);
});
client.on("data", (data) => {
console.log(" {
console.log("与服务器断开连接");
});
const net = require("net");
const server = net.createServer((c) => {
c.on("data", (data) => {
c.write(data.toString());
});
});
server.listen(5000, () => {
console.log("server start port is: " + server.address().port);
});
const net = require("net");
const serverAddress = {
host: "127.0.0.1",
port: 5000,
};
// 创建代理服务器
const server = net.createServer((clientSocket) => {
// 接受client的消息,转发给服务器
clientSocket.on("data", (data) => {
// 将client发来的数据,转发给服务器
const client = net.createConnection(serverAddress, () => {
console.log("proxy send server " + data);
client.write(data);
});
// 将服务器返回的数据,返给client
client.on("data", (data) => {
console.log("proxy send client " + data);
clientSocket.write(data);
client.end();
});
});
});
server.listen(3000, () => {
console.log("proxy server start port is: " + server.address().port);
});
client start port is: 6259
--> 0
1
2
proxy server start port is: 3000
proxy send server0
proxy send client0
proxy send server1
proxy send client1