码迷,mamicode.com
首页 > Web开发 > 详细

nodejs 简单的模拟代理服务器

时间:2020-06-19 16:18:50      阅读:62      评论:0      收藏:0      [点我收藏+]

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

代理前: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

nodejs 简单的模拟代理服务器

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

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!