复制代码代码如下:
Пакет cn.liangjintang.httpproxy;
Импорт java.io.bufferedReader;
импортировать java.io.bytearrayinputstream;
импортировать java.io.ioexception;
импортировать java.io.inputstream;
Импорт java.io.inputStreamReader;
импортировать java.io.outputstream;
импортировать java.net.serversocket;
импортировать java.net.socket;
открытый класс httpproxy {
Статический длинный ThreadCount = 0;
int mytcpport = 8080;
Private Serversocket myserversocket;
Приватная ветка Mythread;
public httpproxy (int port) бросает ioexception {
mytcpport = порт;
myserversocket = new Serversocket (mytcpport);
mythread = new Thread (new Runnable () {
public void run () {
пытаться {
пока (правда)
новая httpsession (myserversocket.accept ());
} catch (ioException ioe) {
}
}
});
mythread.setdaemon (true);
mythread.start ();
}
/**
* Останавливает сервер.
*/
public void Stop () {
пытаться {
myserversocket.close ();
mythread.join ();
} catch (ioException ioe) {
} catch (прерванная экспрессия e) {
}
}
открытый класс httpsession реализует Runnable {
Приватный сокет MySocket;
public httpsession (сокет S) {
mysocket = s;
Потока t = новый поток (это);
T.SetDaemon (True);
t.start ();
}
@Override
public void run () {
пытаться {
++ ThreadCount;
InputStream IS = mySocket.getInputStream ();
if (есть == null)
возвращаться;
окончательный 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)
перерыв;
read = is.read (buf, rlen, bufsize - rlen);
}
BytearrayinputStream HBIS = New BytearRayinputStream (Buf,
0, rlen);
BufferedReader hin = новый буфериальный читатель (
новый InputStreamReader (HBIS));
Хост хост = новый хост ();
{
String String;
логический флаг = false;
while ((string = hin.readline ())! = null) {
if (string.tolaycome (). startSwith ("host:")) {
host.host = string;
flag = true;
}
System.out.println (String);
}
if (! flag) {
mysocket.getOutputStream (). Напишите (
«Ошибка!». GetBytes ());
mysocket.close ();
возвращаться;
}
}
host.cal ();
System.out.println ("Адрес: [" + host.address + "] Порт:"
+ host.port + "/n -------------------/n");
пытаться {
труба (buf, rlen, mysocket, mysocket.getinputstream (),
mysocket.getOutputStream (), хост);
} catch (Exception e) {
System.out.println («Запустить исключение!»);
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')
вернуть SplitByte + 4;
SplitByte ++;
}
возврат 0;
}
void tipe (byte [] запрос, int requestlen, клиент сокета,
Inputstream clientis, outputstream clientos, хост хост)
бросает исключение {
байтовые байты [] = новый байт [1024 * 32];
Сокет сокет = новый сокет (host.address, host.port);
Socket.setsotimeout (3000);
OutputStream OS = socket.getOutputStream ();
Inputstream is = socket.getInputStream ();
пытаться {
делать {
Os.Write (запрос, 0, requestLen);
int resultlen = 0;
пытаться {
while ((resultlen = is.read (байты))! = -1
&&! mysocket.isclosed () &&! socket.isclosed ()) {
clientos.write (байты, 0, resultlen);
}
} catch (Exception e) {
System.out.println («Исключение Target Socket:»
+ 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 ("Исключение клиента:" + e.tostring ());
}
System.out.println ("End, Socket:" + socket.hashcode ());
os.close ();
is.close ();
clientis.close ();
clientos.close ();
Socket.Close ();
mysocket.close ();
}
// Информация о целевом хосте
окончательный класс хост {
публичный строковый адрес;
общественный порт Int;
публичный строковый хост;
public boolean cal () {
if (host == null)
вернуть ложь;
int start = host.indexof (":");
if (start == -1)
вернуть ложь;
int next = host.indexof (':', start + 2);
if (next == -1) {
порт = 80;
address = host.substring (start + 2);
} еще {
address = host.substring (start + 2, next);
port = integer.valueof (host.substring (следующий + 1));
}
вернуть истину;
}
}
}
public static void main (string [] args) {
пытаться {
новый httpproxy (8580);
} catch (ioException ioe) {
System.err.println ("не может запустить сервер:/n" + ioe);
System.Exit (-1);
}
System.out.println ("start!");
пытаться {
System.in.read ();
} catch (throwable t) {
}
System.out.println ("Stop!");
}
}