zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java实现轻量型http代理服务器示例

JAVAHTTP 实现 示例 轻量 代理服务器
2023-06-13 09:15:24 时间

复制代码代码如下:


packagecn.liangjintang.httpproxy;

importjava.io.BufferedReader;
importjava.io.ByteArrayInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.ServerSocket;
importjava.net.Socket;

publicclassHttpProxy{
 staticlongthreadCount=0;
 intmyTcpPort=8080;
 privateServerSocketmyServerSocket;
 privateThreadmyThread;

 publicHttpProxy(intport)throwsIOException{
  myTcpPort=port;
  myServerSocket=newServerSocket(myTcpPort);
  myThread=newThread(newRunnable(){
   publicvoidrun(){
    try{
     while(true)
      newHTTPSession(myServerSocket.accept());
    }catch(IOExceptionioe){
    }
   }
  });
  myThread.setDaemon(true);
  myThread.start();
 }

 /**
 *Stopstheserver.
 */

 publicvoidstop(){
  try{
   myServerSocket.close();
   myThread.join();
  }catch(IOExceptionioe){
  }catch(InterruptedExceptione){
  }
 }

 publicclassHTTPSessionimplementsRunnable{
  privateSocketmySocket;

  publicHTTPSession(Sockets){
   mySocket=s;
   Threadt=newThread(this);
   t.setDaemon(true);
   t.start();
  }

  @Override
  publicvoidrun(){
   try{
    ++threadCount;

    InputStreamis=mySocket.getInputStream();
    if(is==null)
     return;
    finalintbufsize=8192;
    byte[]buf=newbyte[bufsize];
    intsplitbyte=0;
    intrlen=0;
    {
     intread=is.read(buf,0,bufsize);
     while(read>0){
      rlen+=read;
      splitbyte=findHeaderEnd(buf,rlen);
      if(splitbyte>0)
       break;
      read=is.read(buf,rlen,bufsize-rlen);
     }
     ByteArrayInputStreamhbis=newByteArrayInputStream(buf,
       0,rlen);
     BufferedReaderhin=newBufferedReader(
       newInputStreamReader(hbis));
     Hosthost=newHost();
     {
      Stringstring;
      booleanflag=false;
      while((string=hin.readLine())!=null){
       if(string.toLowerCase().startsWith("host:")){
        host.host=string;
        flag=true;
       }
       System.out.println(string);
      }
      if(!flag){
       mySocket.getOutputStream().write(
         "error!".getBytes());
       mySocket.close();
       return;
      }
     }

     host.cal();
     System.out.println("address:["+host.address+"]port:"
       +host.port+"\n-------------------\n");

     try{
      pipe(buf,rlen,mySocket,mySocket.getInputStream(),
        mySocket.getOutputStream(),host);
     }catch(Exceptione){
      System.out.println("RunException!");
      e.printStackTrace();
     }
    }

   }catch(Exceptione){
   }
   System.out.println("threadcount:"+--threadCount);
  }

  /**
  *finadhttpheader
  **/
  privateintfindHeaderEnd(finalbyte[]buf,intrlen){
   intsplitbyte=0;
   while(splitbyte+3<rlen){
    if(buf[splitbyte]=="\r"&&buf[splitbyte+1]=="\n"
      &&buf[splitbyte+2]=="\r"
      &&buf[splitbyte+3]=="\n")
     returnsplitbyte+4;
    splitbyte++;
   }
   return0;
  }

  voidpipe(byte[]request,intrequestLen,Socketclient,
    InputStreamclientIS,OutputStreamclientOS,Hosthost)
    throwsException{
   bytebytes[]=newbyte[1024*32];
   Socketsocket=newSocket(host.address,host.port);
   socket.setSoTimeout(3000);
   OutputStreamos=socket.getOutputStream();
   InputStreamis=socket.getInputStream();
   try{
    do{
     os.write(request,0,requestLen);
     intresultLen=0;
     try{
      while((resultLen=is.read(bytes))!=-1
        &&!mySocket.isClosed()&&!socket.isClosed()){
       clientOS.write(bytes,0,resultLen);
      }
     }catch(Exceptione){
      System.out.println("targetSocketexception:"
        +e.toString());
     }

     System.out.println("proxyrequset-connectbroken,socket:"
       +socket.hashCode());
    }while(!mySocket.isClosed()
      &&(requestLen=clientIS.read(request))!=-1);
   }catch(Exceptione){
    System.out.println("clientSocketexception:"+e.toString());
   }

   System.out.println("end,socket:"+socket.hashCode());
   os.close();
   is.close();
   clientIS.close();
   clientOS.close();
   socket.close();
   mySocket.close();

  }

  //targetHostinfo
  finalclassHost{
   publicStringaddress;
   publicintport;
   publicStringhost;

   publicbooleancal(){
    if(host==null)
     returnfalse;
    intstart=host.indexOf(":");
    if(start==-1)
     returnfalse;
    intnext=host.indexOf(":",start+2);
    if(next==-1){
     port=80;
     address=host.substring(start+2);
    }else{
     address=host.substring(start+2,next);
     port=Integer.valueOf(host.substring(next+1));
    }
    returntrue;
   }
  }
 }

 publicstaticvoidmain(String[]args){
  try{
   newHttpProxy(8580);
  }catch(IOExceptionioe){
   System.err.println("Couldn"tstartserver:\n"+ioe);
   System.exit(-1);
  }
  System.out.println("start!");
  try{
   System.in.read();
  }catch(Throwablet){
  }
  System.out.println("stop!");
 }
}