代理前:client -> server
代理后:client -> proxy -> server
game-client.js:
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("<-- " + data.toString());
});
client.on("end", () => {
console.log("与服务器断开连接");
});
game-server.js:
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);
});
game-proxy-server.js
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 print:
client start port is: 6259
--> 0
<-- 0
--> 1
<-- 1
--> 2
prixy print:
proxy server start port is: 3000
proxy send server0
proxy send client0
proxy send server1
proxy send client1