javascript NodeJS代理服务器:如何将浏览器的http请求发送到internet并写回响应?

vbopmzt1  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(110)

简单的代理服务器
下面的NodeJS TCP服务器编码为在端口8080运行的Live代理。Mozilla Firefox配置在端口8080,向此NodeJS应用程序发送http标头。一切正常。我可以看到命令行中的标题。但是我需要动态地将这些头发送到互联网并获得响应。收到响应后,我需要将其写入服务器套接字中,以便在浏览器上显示。(通常浏览)
我在代码上注解它。请仔细检查代码并给予我一个解决方案。

const net = require('net')
const PORT = 8080

var clients = []

let date_ob = new Date()
let date = ("0" + date_ob.getDate()).slice(-2)
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2)
let year = date_ob.getFullYear()
let hours = date_ob.getHours()
let minutes = date_ob.getMinutes()
let seconds = date_ob.getSeconds()

const server = net.createServer((socket)=>{

    let sock_name = socket.remoteAddress + ":" + socket.remotePort
    clients.push(socket)
    
    socket.on('data', (data)=> {
        console.log(year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds)  
        console.log(sock_name)
/*This "data" should send to internet dynamically like java socket applications and get back the respose*/          
console.log(""+data)        
    })
    
    socket.on('end', ()=>{
      clients.splice(clients.indexOf(socket), 1)
      console.log(sock_name +" left\n")
   })
   
   socket.on('error',(error)=>{
     console.log(error) 
   })       
    
}).listen(PORT)

server.on('error', (error) => {
    console.log(error)  
})

console.log("Server running at port 8080\n")

1.从浏览器接收的数据应该发送到互联网。
1.将响应写回服务器套接字

socket.on('data', (data)=> {    
/*This "data" should send to internet dynamically like java socket applications and get back the respose */         
console.log(""+data)        
})
ohtdti5x

ohtdti5x1#

要创建代理服务器,不仅要有服务器(接收数据),还要有客户端(发送数据)。当然,要将数据发送到任何其他服务器,您需要知道服务器的PORT和HOST(在下面的代码中- remoteHost和remotePort)。
下面是一个示例:

const net = require('node:net');

class ProxyClient {
  constructor(config) {
    this.config = config;
  }

  async setup() {
    const { proxyClient } = this.config;
    if (!proxyClient) {
      return;
    }

    const { localPort, remoteHost, remotePort } = proxyClient;
    const serviceSocket = await new Promise((resolve) => {
      const socket = new net.Socket();
      socket.connect(remotePort, remoteHost, () => resolve(socket));
    });

    await new Promise((resolve) => {
      const server = net.createServer((proxyServerSocket) => {
        proxyServerSocket.on('data', (message) => {
          serviceSocket.write(message);
        });
        serviceSocket.on('data', (message) => {
          proxyServerSocket.write(message);
        });
        proxyServerSocket.on('error', (error) => {
          console.log('Proxy server error', error);
        });
      });
      server.listen(localPort, '0.0.0.0', () => resolve());
    });
  }
}

const proxy = new ProxyClient({
  localPort: 8080,
  remoteHost: '192.192.192.192',
  remotePort: 4321,
});

proxy.setup()
  .then(()=> console.log('proxy server started'))
  .catch(err => console.error(err);

相关问题