/**
* 方法名称:runServer<p>
* 方法功能:运行代理服务器<p>
* 参数说明: <p>
* 返回:void <p>
* 作者:李明
* 日期:2006年3月9日
* @throws IOException
*/
public void runServer() throws IOException
{
// 创建代理服务器监听,端口默认为9999(可以通过属性文档修改其他端口)
ServerSocket ss = new ServerSocket(localport);
final com.zte.ums.zxnm01.cpe.common.http.ProxyUtil proxyUtil = new com.zte.ums.zxnm01.cpe.common.http.ProxyUtil();
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
while(true)
{
Socket client = null, server = null;
try
{
// 等待客户连接
client = ss.accept();
log.info("*******Client logon*******");
log.info(client);
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// 连接真实的服务器,如果不能连接成功,将向客户发送错误信息,断开本次连接
// 并且继续等待连接.
try
{
server = new Socket(host, remoteport);
}
catch(IOException e)
{
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
out.flush();
client.close();
continue;
}
// 得到连接服务器的输入输出流.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// 构建一个单独线程读客户请求并传给服务器,此线程为异步.
Thread t = new Thread()
{
public void run()
{
int bytesRead;
String context = null;
try
{
while((bytesRead = streamFromClient.read(request)) != -1)
{
streamToServer.write(request, 0, bytesRead);
context = new String(request).trim();
streamToServer.flush();
}
// 打印客户浏览器发来的信息
log.info("#################S##############");
log.info(context);
log.info("#################E##############");
// 解析发来的信息,获取请求的主机地址和端口.
proxyUtil.setUrl(context);
host = proxyUtil.getHost();
remoteport = proxyUtil.getPort();
log.info("host : '" + host + "'" + " port : '" + remoteport + "'");
}
catch(IOException e)
{
// e.printStackTrace();
}
// 关闭请求服务器连接,屏蔽无意义的异常,减少代理服务器负担.
try
{
streamToServer.close();
}
catch(IOException e)
{
// e.printStackTrace();
}
}
};
// 开启客户端到服务器请求线程
t.start();
// 读服务器的请求,成功后返回信息给客户端.
int bytesRead;
try
{
while((bytesRead = streamFromServer.read(reply)) != -1)
{
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
}
catch(IOException e)
{
// e.printStackTrace();
}
// 关闭客户连接.
streamToClient.close();
}
catch(IOException e)
{
System.err.println(e);
}
finally
{
try
{
if(server != null)
{
server.close();
}
if(client != null)
{
client.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
posted on 2006-04-28 11:24
崛起的程序员 阅读(240)
评论(0) 编辑 收藏 所属分类:
java