nodejs 简单的模拟代理服务器

2021-02-02 23:15

阅读:557

标签:address   href   nts   create   let   tostring   res   server   请求   

  • https://nodejs.org/api/net.html#net_net_createconnection

代理前: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(" {
  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
 1
 2

prixy print:

proxy server start port is: 3000
proxy send server0
proxy send client0
proxy send server1
proxy send client1

nodejs 简单的模拟代理服务器

标签:address   href   nts   create   let   tostring   res   server   请求   

原文地址:https://www.cnblogs.com/ajanuw/p/13163184.html


评论


亲,登录后才可以留言!