Java开发代理服务器,使用Java开发代理服务器,有相关源码
实用第一智慧密集
method=1;
s2="HTTP/1.0200Connectionestablished\r\n";s2=s2+"Proxy-agent:proxy\r\n\r\n";buf2=s2.getBytes();
out.write(buf2);out.flush();
}
if(s.indexOf("POST")!=-1)method=2;
//如读到POST请求
if(s.indexOf("doc.guandang.net;)!=-1&&s.indexOf("HTTP/")!=-1){
//从所读数据中取域名和端口号
s1=s.substring(s.indexOf("doc.guandang.net;)+7,s.indexOf("
HTTP/"));
s1=s1.substring(0,s1.indexOf("/"));if(s1.indexOf(":")!=-1){s2=s1;
s1=s1.substring(0,s1.indexOf(":"));s2=s2.substring(s2.indexOf(":")+1);port=Integer.parseInt(s2);method=0;}}
if(s1!=null){
client=newSocket(s1,port);
//根据读到的域名和端口号建立套接字
in1=newDataInputStream(client.getInputStream());out1=newDataOutputStream(client.getOutput-Stream());
if(in1!=null&&out1!=null&&client!=null){if(method==0){
//如读到GET请求,向外网发出GET请求
out1.write(buf,0,readbytes);out1.flush();while(true){//循环try{
if(readbytes1==-1)break;
//无数据则退出循环
//从外网读数据,并返回给内网相应客户端readbytes1=in1.read(buf,0,10000);if(readbytes1>0){
out.write(buf,0,readbytes1);out.flush();}
}catch(Exceptione){break;}//异常则退出}}
if(method==1){//如读到CONNECT请求//建立线程,用于从外网读数据,并返回给内网客户端
HTTPServerThread1thread1=newHTTPServer-Thread1(in1,out);
while(true){//循环try{
if(readbytes1==-1)break;//无数据则退出循环readbytes1=in.read(buf,0,10000);
//从内网读数据
if(readbytes1>0){//读到数据,则发送给外网out1.write(buf,0,readbytes1);out1.flush();}
}catch(Exceptione1){break;}}
}
if(method==2){//如读到POST请求//向外网发送POST请求
out1.write(buf,0,readbytes);out1.flush();
//建立线程,用于从外网读数据,并返回给内网客户端
HTTPServerThread1thread1=newHTTPServer-Thread1(in1,out);
while(true){//循环try{
if(readbytes1==-1)break;//无数据则退出循环readbytes1=in.read(buf,0,10000);
//从内网读数据
if(readbytes1>0){//读到数据,则发送给外网out1.write(buf,0,readbytes1);out1.flush();}
}catch(Exceptione1){break;}}}}}}}
//执行关闭操作
if(in1!=null)in1.close();if(out1!=null)out1.close();if(client!=null)client.close();if(in!=null)in.close();if(out!=null)out.close();
if(connection!=null)connection.close();}catch(IOExceptione){}}}
HTTPServerThread1类用于HTTP代理中读因特网返回数
据,并发送给客户端,实现代码如下:
//本线程类用于HTTP代理中,从外网读数据,并发送给内网客户//端
classHTTPServerThread1extendsThread{privateDataInputStreamin;//读数据privateDataOutputStreamout;//写数据
publicHTTPServerThread1(DataInputStream_in,DataOut-putStream_out){
in=_in;out=_out;start();}
publicvoidrun(){
//线程运行函数,循环读取返回数据,并发送给相关客户端
2010.9
电脑编程技巧与维护
热门文档