http代理工作原理(1)(二)

2014-11-24 11:14:50 · 作者: · 浏览: 1
nt.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*

Title: SimpleHttpProxy1

*

Description:

*

Copyright: Copyright (c) 2006

* @author xuesong.net
* @version 1.0
*/
public class SimpleHttpProxy1
{
public static final int PORT = 6666;
public static final byte[] CRLF = new byte[]{0x0D, 0x0A};
/**
* @param args
*/
public static void main(String[] args)
{
ServerSocket socketServer = null;
BlockingQueue blockingQueue = new ArrayBlockingQueue(1024);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(512, 1024, 30000, TimeUnit.SECONDS, blockingQueue);
try
{
socketServer = new ServerSocket(PORT);
while(true)
{
try
{
final Socket socket = socketServer.accept();
Runnable job = new Runnable(){
public void run(){
service(socket);
}
};
threadPoolExecutor.execute(job);
}
catch(SocketTimeoutException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(socketServer != null)
{
try
{
socketServer.close();
}
catch(IOException e)
{
}
}
}
}
private static void service(Socket socket)
{
Socket remote = null;
try
{
socket.setSoTimeout(2000);
socket.setKeepAlive(false);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
remote = new Socket("127.0.0.1", 8888);
InputStream remoteInputStream = remote.getInputStream();
OutputStream remoteOutputStream = remote.getOutputStream();
try
{
copy(inputStream, remoteOutputStream, 4096);
}
catch(SocketTimeoutException e)
{
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
remote.setSoTimeout(10000);
copy(remoteInputStream, outputStream, 4096);
}
catch(SocketTimeoutException e)
{
}
catch(Exception e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(socket != null)
{
socket.close();
}
}
catch(IOException e)
{
}
try
{
if(remote != null)
{
remote.close();
}
}
catch(IOException e)
{
e.printStackTrace();