Java开发代理服务器,使用Java开发代理服务器,有相关源码
PROGRAMLANGUAGE
bytebuf[]=newbyte[10000];while(true){//循环try{
if(readbytes==-1)break;//无数据则退出循环readbytes=in.read(buf,0,10000);if(readbytes>0){
out.write(buf,0,readbytes);out.flush();}
}catch(Exceptione){break;}//异常则退出循环}}SockSServerThread类用于Socks代理中读客户端请求,并
发送给因特网,实现代码如下:
编程语言
//发送SOCK5应答buf1[0]=5;buf1[1]=0;
out.write(buf1,0,2);out.flush();readbytes=in.read(buf,0,10000);
//继续读SOCK5请求
if(readbytes>0){//读到SOCK5请求
if(buf[0]==5&&buf[1]==1&&buf[2]==0&&buf[3]==
1){//TCP请求
//从该请求中取要连接的IP地址和端口号,并建立
//TCP套接字
ip=bytes2int(buf[4])+"."+bytes2int(buf[5])+"."+bytes2int(buf[6])+"."+bytes2int(buf[7]);port=buf[8]*256+buf[9];client=newSocket(ip,port);
in1=newDataInputStream(client.getInputStream
());
out1=newDataOutputStream(client.getOutput-Stream());
//发送SOCK5应答
ip1=client.getLocalAddress().getAddress();port1=client.getLocalPort();buf[1]=0;
buf[4]=ip1[0];buf[5]=ip1[1];buf[6]=ip1[2];buf[7]=ip1
[3];
buf[8]=(byte)(port1>>8);buf[9]=(byte)(port1&0xff);out.write(buf,0,10);out.flush();//建立线程,用于给客户端返回数据
SOCKSServerThread1thread1=new
SOCKSServerThread1(in1,out);
while(true){//循环读数据try{
if(readbytes1==-1)break;//无数据则退出循环readbytes1=in.read(buf1,0,10000);
//从客户端读数据
if(readbytes1>0){//读到数据,则发送给外网out1.write(buf1,0,readbytes1);out1.flush();}
}catch(Exceptione1){break;}}}}}
if(buf[0]==4){//读到SOCK4请求
port=buf[2]*256+buf[3];//从请求中取端口号
if(buf[4]==0&&buf[5]==0&&buf[6]==0&&buf[7]!=
0&&buf[8]==0){
//如请求中为域名s=newString(buf);s=s.substring(9);
s=s.substring(0,s.indexOf("\0"));}
else{//如请求中为IP地址
//本线程类用于SOCKS代理中,从内网读数据,并发送给外网classSOCKSServerThreadextendsThread{privateSocketconnection;
intbytes2int(byteb){//将byte类型转换为int类型intmask=0xff;inttemp=0;intres=0;res<<=8;
temp=b&mask;res|=temp;returnres;}
publicSOCKSServerThread(Socket_connection){//构造函数
connection=_connection;start();}
publicvoidrun(){//线程运行函数
bytebuf[]=newbyte[10000],buf1[]=newbyte[10000],buf2[]=newbyte[10000];
intreadbytes=0,readbytes1=0,readbytes2=0;DataInputStreamin=null,in1=null;
DataOutputStreamout=null,out1=null;Strings=null,s1=null,s2=null;inti;
intport=0,port1=0;Stringip=null;
Socketclient=null;
byteip1[]=newbyte[4],ip2[]=newbyte[4];try{
in=newDataInputStream(connection.getInputStream());out=newDataOutputStream(connection.getOutput-Stream());
if(in!=null&&out!=null){
readbytes=in.read(buf,0,10000);//从客户端读数据if(readbytes>0){//读到数据
读到请求
2010.9
21
热门文档