http代理工作原理(3)(三)

2014-11-24 11:14:48 · 作者: · 浏览: 6
* 因此使用timeout来解决阻塞的问题
* 超时的时候自动退出线程, 否则该线程就无法释放了
*/
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();
}
}
}
public static byte[] readLine(InputStream stream) throws IOException
{
int b = -1;
ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
while((b = stream.read()) != -1)
{
if(b == '\n')
{
bos.write(b);
break;
}
bos.write(b);
}
return bos.toByteArray();
}
public static void copy(InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException
{
int length = 0;
byte[] buffer = new byte[bufferSize];
while((length = inputStream.read(buffer, 0, bufferSize)) > -1)
{
outputStream.write(buffer, 0, length);
}
outputStream.flush();
}
public static void copy(InputStream inputStream, OutputStream outputStream, int bufferSize, long size) throws IOException
{
if(size > 0)
{
int readBytes = 0;
long count = size;
int length = Math.min(bufferSize, (int)(size));
byte[] buffer = new byte[length];
while(count > 0)
{
if(count > length)
{
readBytes = inputStream.read(buffer, 0, length);
}
else
{
readBytes = inputStream.read(buffer, 0, (int)count);
}
if(readBytes > 0)
{
outputStream.write(buffer, 0, readBytes);
count -= readBytes;
}
else
{
break;
}
}
outputStream.flush();
}
}
} www.2cto.com
到此为止,一个简易的http代理已经完成了, 虽然他还有很多不完善的地方, 但是已经基本上能正常完成我们要求的功能了.
如果需要让他更加的稳定,性能更好一点,具有更强的容错性,甚至可扩展性,还有很多工作要做。这里就不多写了。有兴趣的朋友可以参考我前面的博客。