⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpproxy.java

📁 网络代理服务器的设计与实现 实现对网络的管理
💻 JAVA
字号:
import java.net.*;
import java.util.*;
import java.io.*;
import sun.misc.BASE64Decoder;
import javax.swing.JOptionPane;

//代理服务器的线程服务类
public class httpProxy extends Thread{
    //尝试对远程连接的次数
	static public int CONNECT_RETRIES=5;
	//间隔多少时间尝试一次对远程连接
	static public int CONNECT_PAUSE=5;
	//等待用户从浏览器发布数据的时间
	static public int TIMEOUT=100;
	//Socket的输入缓冲
	static public int BUFSIZ=100*1024;   //512K
	public static int ProxytoUserPort=808;	
	protected  ServerSocket serversock;
	public static String head="";
	protected Socket socket;
	private boolean flag;
	//private String reqFileName=null;
	
	public static long acceptSum=0;
	public static long sendSum=0;
	public String[] IPaddr;
	public static int CONNECTIONNUM=5;
	

	
	//初始化并启动代理服务
	public httpProxy(ServerSocket serversock){
		this.serversock=serversock;
		acceptSum=0;
		sendSum=0;
		IPaddr=new String[CONNECTIONNUM];
		for(int i=0;i<CONNECTIONNUM;i++){
			IPaddr[i]="";
		}
	}//HttpProxy	
	
	public void run(){
		while(true){
			try{
				socket=serversock.accept();
				(new thread(socket)).start();
			}catch(Exception e){}
				
		}
	}	
	
	class thread extends Thread{
		private Socket socket;
		
		public thread(Socket s){
			this.socket=s;
		}
		
		public void run(){
			String host;
			String[] buffer;
			String reqFileName=null;
			String name,passWord;
			String pszCode,pszText;
			int port=80;
			Socket outbound=null;
			
			try{
				buffer=new String[20];
				for(int i=0;i<20;i++)
					buffer[i]="";
				socket.setSoTimeout(TIMEOUT);
				String pAuthorization = findpAuthorization(socket,buffer);	
				
				if(pAuthorization.equals("")){
					sendAuthorization(socket.getOutputStream());
				}else{	
					System.out.println("收到密码");
					pszCode=pAuthorization.substring(27);
					byte[] bytes0=new BASE64Decoder().decodeBuffer(pszCode);
					pszText=new String(bytes0);
					int at=pszText.indexOf(":");
					name=pszText.substring(0,at);
					passWord=pszText.substring(at+1);
					boolean userLoadFlag=eventFrame.userPanel.userLoad(name,passWord);
					
				//InputStream is=socket.getInputStream();	
				//host=getHost(is);
				//writeLog(socket);
					if(userLoadFlag){	
						host=getHost();
						writeLog(socket);
						if(timePane.getFlag()){	
							if(filterPane3.find(host)==false){ 	
								flag=cachePane.flag;						
								reqFileName=getFileName();		
				    
								//在缓存中找到该文件并且使用缓存,则直接在缓存中读取
								if(findFile(reqFileName)&&flag){
									String folder=cachePane.folder;
									pipe(folder+"\\"+reqFileName,socket.getOutputStream());
								}
								else{					
									writeLog(host);				
									while(true){
										int n=-1;
										n=host.indexOf(":"); // http://www.sina.com.cn:8080
										if(n!=-1){
											port=Integer.parseInt(host.substring(n+1));
											host=host.substring(0,n);
										}
					
										int retry=CONNECT_RETRIES;					
										while(retry--!=0){
											try{
												//和远程主机建立连接
												outbound=new Socket(host,port);
												break;
											}
											catch(Exception e){
												e.printStackTrace();
											}					
											Thread.sleep(CONNECT_PAUSE);
										}
					
										if(outbound==null) 
											break;
										outbound.setSoTimeout(TIMEOUT);
										//OutputStream os1=outbound.getOutputStream();
					
										//byte[] bytes=head.getBytes();
										//os1.write(bytes,0,bytes.length);
					
										pipe(socket.getInputStream(),outbound.getInputStream(),socket.getOutputStream(),outbound.getOutputStream(),reqFileName,buffer);
										outbound.close();
										break;
									}
								}	
							}else{
								pipe("ban.txt",socket.getOutputStream());	
							}
						}else{
							pipe("timeban.txt",socket.getOutputStream());
						}
					}else{
						pipe("load.txt",socket.getOutputStream());
					}
				}
			}catch(Exception e){e.printStackTrace();}		
			finally{
				try{socket.close();
					System.out.println("Socket 关闭");
				}
				catch(Exception e1){e1.printStackTrace();}			
			}			
		}//run
	}
	
//	写日志信息
	public static void  writeLog(Socket sock){
		//获取可户短的IP 地址
		//InetAddress clientInetAddress=sock.getInetAddress();
		try { 
			String logPath=portPane.getLogPath();
			String logFile="log";
			logFile=logPath+"\\"+logFile;
			Calendar  date=new GregorianCalendar();  
		    int year=date.get(Calendar.YEAR);
		    int month=date.get(Calendar.MONTH)+1;		    
		    int data=date.get(Calendar.DAY_OF_MONTH);
		    int hour=date.get(Calendar.HOUR_OF_DAY);
		    int minute=date.get(Calendar.MINUTE);
		    int second=date.get(Calendar.SECOND);
		    
		    logFile+=year;
		    logFile+=(month<10?"0":"")+month;
		    logFile+=(data<10?"0":"")+data;
		    logFile+=".txt";
		    

		    //  按日期每天生成一个日志文件  
		    PrintWriter outl = new PrintWriter(new FileWriter(logFile,true)); 
		    outl.print("["+hour+":"+minute+":"+second+ "]  Accept: " +sock.getInetAddress().getHostAddress()+"  "+sock.getInetAddress().getHostName()); 
		    outl.println("    "+head);
		    
		    eventFrame.disPlay.writeArea("Accept: " +sock.getInetAddress().getHostAddress()+"  "+sock.getInetAddress().getHostName());
		    eventFrame.disPlay.writeArea("    "+head+"\n");
		    outl.close();
		    }catch (IOException ex) { 
		} 
	}
	
	public static void writeLog(String host){
		try { 
			String logPath=portPane.getLogPath();
			String logFile="log";
			logFile=logPath+"\\"+logFile;
			
			Calendar  date=new GregorianCalendar();  
		    int year=date.get(Calendar.YEAR);
		    int month=date.get(Calendar.MONTH)+1;		    
		    int data=date.get(Calendar.DAY_OF_MONTH);
		    int hour=date.get(Calendar.HOUR_OF_DAY);
		    int minute=date.get(Calendar.MINUTE);
		    int second=date.get(Calendar.SECOND);
		    
		    logFile+=year;
		    logFile+=(month<10?"0":"")+month;
		    logFile+=(data<10?"0":"")+data;
		    logFile+=".txt";

		    //  按日期每天生成一个日志文件 
		    PrintWriter outl = new PrintWriter(new FileWriter(logFile,true)); 
		    InetAddress serverInetAddress=getServerInetAddress(host);
		    outl.println("["+hour+":"+minute+":"+second+ "]  Visit:  " +serverInetAddress.toString());
		    eventFrame.disPlay.writeArea("Visit:  " +serverInetAddress.toString()+"\n");
		    
		    outl.close(); 
		    }catch (Exception ex) { 
		} 
	}
	
	public String getIP(Socket s){
		return (s.getInetAddress().getHostAddress());		
	}
	
	public static void writeLog1(String msg){
		try { 
			String logPath=portPane.getLogPath();
			String logFile="log";
			logFile=logPath+"\\"+logFile;
			
			Calendar  date=new GregorianCalendar();  
		    int year=date.get(Calendar.YEAR);
		    int month=date.get(Calendar.MONTH)+1;		    
		    int data=date.get(Calendar.DAY_OF_MONTH);
		    int hour=date.get(Calendar.HOUR_OF_DAY);
		    int minute=date.get(Calendar.MINUTE);
		    int second=date.get(Calendar.SECOND);
		    
		    logFile+=year;
		    logFile+=(month<10?"0":"")+month;
		    logFile+=(data<10?"0":"")+data;
		    logFile+=".txt";

		    //  按日期每天生成一个日志文件 
		    PrintWriter outl = new PrintWriter(new FileWriter(logFile,true));
		    outl.println(msg);
		    eventFrame.disPlay.writeArea(msg+"\n");		    
		    outl.close(); 
		    }catch (Exception ex) { 
		} 
	}
	
	public static void writeLog(String msg,String host){
		try { 
			String logPath=portPane.getLogPath();
			String logFile="log";
			logFile=logPath+"\\"+logFile;
			
			Calendar  date=new GregorianCalendar();  
		    int year=date.get(Calendar.YEAR);
		    int month=date.get(Calendar.MONTH)+1;		    
		    int data=date.get(Calendar.DAY_OF_MONTH);
		    int hour=date.get(Calendar.HOUR_OF_DAY);
		    int minute=date.get(Calendar.MINUTE);
		    int second=date.get(Calendar.SECOND);
		    
		    logFile+=year;
		    logFile+=(month<10?"0":"")+month;
		    logFile+=(data<10?"0":"")+data;
		    logFile+=".txt";

		    //  按日期每天生成一个日志文件  
		    PrintWriter outl = new PrintWriter(new FileWriter(logFile,true)); 
		    outl.println(msg + host);
		    eventFrame.disPlay.writeArea(msg + host +"\n");
		    
		    outl.close(); 
		    }catch (Exception ex) { 
		} 
	}
	
	
	public static InetAddress getServerInetAddress(String host) throws Exception{
		InetAddress serverInetaddress=null;
        //获取WEB服务器IP			
		if('1'<host.charAt(0)&&host.charAt(0)<'9'){           //如果用户是以IP文本串来获取IP
			serverInetaddress=InetAddress.getByAddress(host.getBytes());
		}
		else{                                                 //如果用户是以域名来获取IP
			serverInetaddress=InetAddress.getByName(host);          //ARP协议
		}
		return serverInetaddress;
	}
	
	public static String getHost() throws IOException{
		String host=null;
		host=head;      		
		
		int n=host.indexOf("//");
		if(n!=-1) 
			host=host.substring(n+2);//  host=news.sina.com.cn/c/2007-05-17/094913009832.shtml
		n=host.indexOf('/');
		if(n!=-1) 
			host=host.substring(0,n);	
		return host;		
	}//gethost	
	
	public String getFileName(){
		String fileName=head;
		int n=fileName.lastIndexOf(" HTTP/1.0");
	    fileName=fileName.substring(0,n);
	    n=fileName.lastIndexOf("/");
	    fileName=fileName.substring(n+1);
	    return fileName;
	}		
	
	public boolean findFile(String filename){
		if(filename.equals(null)) return false;
		try{
			BufferedReader in=new BufferedReader(new FileReader("web\\cacheindex.txt"));
			String readFileName,timeStr;
			long time;
			int maxTime=Integer.parseInt(cachePane.maxTime);
		    while((readFileName=in.readLine())!=null){
		    	timeStr=in.readLine();
		    	if(readFileName.equals(filename)){
		    		time=Long.parseLong(timeStr);
		    		if(((new Date()).getTime()-time)<maxTime*60000)
		    			return true;
		    	}		    		
		    }		    
		}catch(Exception e){}
		return false;
	}
	
	
	  // pipe(socket.getInputStream(),outbound.getInputStream(),socket.getOutputStream(),os1);
	void pipe(InputStream is0,InputStream is1,OutputStream os0,OutputStream os1,String filename,String[] b) {
		try{
			int i;
			byte bytes[]=new byte[BUFSIZ];
			String folder=cachePane.folder;
			
			for(i=0;b[i].equals("")==false;i++){
				bytes=b[i].getBytes();
				os1.write(bytes,0,bytes.length);
				os1.flush();
				System.out.println(b[i]);
			}
			System.out.println("wancheng");
			while(true){
				try{
					//将客户端输入流写入服务器端输出流
					//如果 inputstream没有数据,read方法阻塞
					if((i=is0.read(bytes))>0){
						os1.write(bytes,0,i);
						os1.flush();
						String str=new String(bytes,0,bytes.length);
						System.out.println(str+  "  submit   " +i);
					}
					else if(i<0)
						     break;  
				}catch(InterruptedIOException e){}
				
				try{
					//将服务端输入流写入客户端输出流
					//如果 inputstream没有数据,read方法阻塞
					//if(!reqFileName.equals(null)){
					//     FileOutputStream fout=new FileOutputStream(folder+reqFileName);
					
					if((i=is1.read(bytes))>0){
						os0.write(bytes,0,i);
						os0.flush();
						String str=new String(bytes);
						System.out.println(str +"  accept   " +i);
						acceptSum = acceptSum+i;
						sendSum = sendSum+i;
						if(filename.equals("")==false&&flag){
							
							//System.out.println(folder+"\\"+reqFileName);
							FileOutputStream fout=new FileOutputStream(folder+"\\"+filename);
							fout.write(bytes,0,i);
							fout.flush();
							fout.close();
							writeIndex(folder,filename);
						}
					}
					else if(i<=0){
						break; 
					} 
				}catch(InterruptedIOException e){}
			}
		}catch(Exception e){e.printStackTrace();}
	}
	
	void pipe(String fileName,OutputStream out){
		try{
			int i;
			byte[] bytes=new byte[BUFSIZ];
			FileInputStream fin=new FileInputStream(fileName);
			while(true){
				if((i=fin.read(bytes))>0){
					out.write(bytes,0,i);
					out.flush();
					sendSum = sendSum+i;
				}
				else if(i<=0)
					break;
			}
			fin.close();
		}catch(Exception e){}
	}
	
	public void writeIndex(String folder,String reqFileName){
		int maxRow=Integer.parseInt(cachePane.maxRow);
		int i=0;
		String str;
		try{
			BufferedReader in=new BufferedReader(new FileReader("web\\cacheindex.txt"));
			BufferedWriter out=new BufferedWriter(new FileWriter("web\\cachetemp.txt",false));
			while((i<=(maxRow+maxRow-2))&&(str=in.readLine())!=null){
				out.write(str);
				out.newLine();
				i++;
			}
			while((str=in.readLine())!=null){
				File f=new File(folder+"\\"+reqFileName);
				f.delete();
				str=in.readLine();
			}
			out.flush();
		    out.close();
		    in.close();
			
			in=new BufferedReader(new FileReader("web\\cachetemp.txt"));
			out=new BufferedWriter(new FileWriter("web\\cacheindex.txt",false));
			out.write(reqFileName);
			out.newLine();
			out.write(String.valueOf((new Date()).getTime()));
			out.newLine();
			while((i<=(maxRow+maxRow-2))&&(str=in.readLine())!=null){
				out.write(str);
				out.newLine();
				i++;
			}
			out.flush();
			out.close();
			in.close();
			File f=new File("web\\cachetemp.txt");
			f.delete();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public boolean IPExist(String ip){
		boolean flag=false;
		for(int i=0;i<CONNECTIONNUM;i++){
			if(IPaddr[i].equals(ip)){
				flag=true;
				break;
			}
		}
		return flag;
	}
	
	public String findpAuthorization(Socket s,String[] b) throws Exception {
		String str="";
		int i=0;
		InputStream is=s.getInputStream();	
		DataInputStream dis=new DataInputStream(is);
		head=dis.readLine();
		b[i]=head;
		i++;
		writeLog1(head);
		
		while(!(str=dis.readLine()).equals("")){
			b[i++]=str;
			if(str.substring(0,8).equals("Proxy-Au"))
				break;
		}
		return str;
	}
	
	public void sendAuthorization(OutputStream os){
		String str;
		byte[] bytes=new byte[BUFSIZ];
		try{
			str="HTTP/1.1 407 Proxy authorization required\r\n";
			bytes=str.getBytes();
			os.write(bytes,0,bytes.length);
			str="Proxy-agent:Ag-PersonalProxy/1.0\r\n";
			bytes=str.getBytes();
			os.write(bytes,0,bytes.length);
			str="Proxy-authenticate:basic realm=\"PersonalProxy\"\r\n";
			bytes=str.getBytes();
			os.write(bytes,0,bytes.length);
		}catch(Exception e){}
	}

	public void close(){
		try{
		    serversock.close();
		}
		catch(Exception e){}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -