Skip to content

Got error : ConnectionReset: Connection reset by peer (os error 54) using Deno.copy in http proxy function #10430

@diqye

Description

@diqye

I want to write a http proxy, but got a error , as below is my all code
image

const port = 7700;
const server = Deno.listen({ port });

console.log("Proxy stared that listening on " + port);
let decoder = new TextDecoder();
let encoder = new TextEncoder();

async function runProxy(){
  let conn = await server.accept();
  runProxy();
  let firstbit = new Uint8Array(1024);
  await conn.read(firstbit)
  let firstLine = decoder.decode(firstbit).split("\n")[0];
  let urlStr = firstLine.split(" ")[1];
  let url =  new URL(urlStr.startsWith("http")?urlStr:"http://"+urlStr);
  let hostname = url.hostname;
  let port = parseInt(url.port || "80");
  console.log(hostname,port,urlStr)
  let remote = await Deno.connect({
    port,
    hostname
  });
  await remote.write(firstbit);
  Deno.copy(conn,remote);
  Deno.copy(remote,conn);
  // console.log("==============")
  // pipe(remote,conn,"rmeote->conn").then(()=>{
  //   // conn.close();
  //   // remote.close();
  // });
  // pipe(conn,remote,"conn->remote").then(()=>{
  //   // conn.close();
  //   // remote.close();
  // })
}

async function pipe(src:Deno.Conn<Deno.NetAddr>,dist:Deno.Conn<Deno.NetAddr>,flag:string){
  while(true){
    let buf = new Uint8Array(1024);
    try{
      let n = await src.read(buf);
      if(n == null){
        break;
      }else{
        console.log(flag,decoder.decode(buf),n);
        await dist.write(buf)
      }
    }catch(e){
      console.dir(e);
      break;
    }
  }
}

runProxy();

run

➜  myproxy git:(main) ✗ deno run --allow-net --unstable  proxy.ts

then set http proxy in your system

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions