Java implementation of lightweight HTTP proxy Server sample _java

Source: Internet
Author: User

Copy Code code as follows:

Package cn.liangjintang.httpproxy;

Import Java.io.BufferedReader;
Import Java.io.ByteArrayInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.net.ServerSocket;
Import Java.net.Socket;

public class Httpproxy {
static long threadcount = 0;
int mytcpport = 8080;
Private ServerSocket myServerSocket;
Private Thread mythread;

public httpproxy (int port) throws IOException {
Mytcpport = port;
myServerSocket = new ServerSocket (mytcpport);
Mythread = new Thread (new Runnable () {
public void Run () {
try {
while (true)
New HTTPSession (Myserversocket.accept ());
catch (IOException IoE) {
}
}
});
Mythread.setdaemon (TRUE);
Mythread.start ();
}

/**
* Stops the server.
*/

public void Stop () {
try {
Myserversocket.close ();
Mythread.join ();
catch (IOException IoE) {
catch (Interruptedexception e) {
}
}

public class HTTPSession implements Runnable {
Private Socket Mysocket;

Public HTTPSession (Socket s) {
Mysocket = s;
Thread t = new thread (this);
T.setdaemon (TRUE);
T.start ();
}

@Override
public void Run () {
try {
++threadcount;

InputStream is = Mysocket.getinputstream ();
if (is = = null)
Return
Final int bufsize = 8192;
byte[] buf = new Byte[bufsize];
int splitbyte = 0;
int rlen = 0;
{
int read = 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);
}
Bytearrayinputstream hbis = new Bytearrayinputstream (buf,
0, Rlen);
BufferedReader hin = new BufferedReader (
New InputStreamReader (Hbis));
Host host = new host ();
{
string string;
Boolean flag = 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");

try {
Pipe (buf, Rlen, Mysocket, Mysocket.getinputstream (),
Mysocket.getoutputstream (), host);
catch (Exception e) {
System.out.println ("Run exception!");
E.printstacktrace ();
}
}

catch (Exception e) {
}
System.out.println ("ThreadCount:" +--threadcount);
}

/**
* Finad HTTP Header
**/
private int Findheaderend (final byte[] buf, int rlen) {
int splitbyte = 0;
while (Splitbyte + 3 < Rlen) {
if (buf[splitbyte] = = ' \ r ' && Buf[splitbyte + 1] = = ' \ n '
&& Buf[splitbyte + 2] = = ' \ r '
&& Buf[splitbyte + 3] = = ' \ n ')
return splitbyte + 4;
splitbyte++;
}
return 0;
}

void pipe (byte[] request, int requestlen, Socket client,
InputStream Clientis, OutputStream Clientos, host host)
Throws Exception {
byte bytes[] = new byte[1024 * 32];
Socket socket = new socket (host.address, host.port);
Socket.setsotimeout (3000);
OutputStream OS = Socket.getoutputstream ();
InputStream is = Socket.getinputstream ();
try {
do {
Os.write (Request, 0, Requestlen);
int resultlen = 0;
try {
while ((Resultlen = is.read (bytes))!=-1
&&!mysocket.isclosed () &&!socket.isclosed ()) {
Clientos.write (bytes, 0, Resultlen);
}
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Target Socket exception:"
+ e.tostring ());
}

System.out.println ("Proxy requset-connect broken,socket:"
+ Socket.hashcode ());
while (!mysocket.isclosed ()
&& (Requestlen = clientis.read (Request))!=-1);
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Client Socket exception:" + e.tostring ());
}

System.out.println ("End,socket:" + socket.hashcode ());
Os.close ();
Is.close ();
Clientis.close ();
Clientos.close ();
Socket.close ();
Mysocket.close ();

}

  //target Host info
  final class Host {
   public String address;
   public int port;
   public String host;

   public Boolean cal () {
    if (host = null)
      return false;
    int start = Host.indexof (":");
    if (start = = 1)
     return false;
    int next = Host.indexof (': ', start + 2);
    if (next = 1) {
     port =;
     address = host.substring (start + 2);
    } else {
     address = host.substring (start + 2, next);
     port = integer.valueof (host.substring (next + 1));
    }
    return true;
   }
  }
 }

public static void Main (string[] args) {
try {
New Httpproxy (8580);
catch (IOException IoE) {
System.err.println ("couldn ' t start server:\n" + IoE);
System.exit (-1);
}
System.out.println ("start!");
try {
System.in.read ();
catch (Throwable t) {
}
System.out.println ("stop!");
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.