java写的一个网络代理小工具

最近老师给的项目刚做完,闲着无聊就想着编点东西。实验室中通过代理上网的,所以我就试着编写了网络代理小工具。代码如下:

package com.lqz;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.lang.Runnable;
/**
 * 
 * @author feifan
 * @category javaCCproxy
 * @version 1.5.0
 * @copyrihgt private
 * 
 * 
 */
public class UsingGoAgent {
	private ServerSocket server=null;
	private Socket client=null;
	public UsingGoAgent() throws Exception {
		server=new ServerSocket(809);
		service();
	}
	public void service() throws IOException{
		while(true){
			client=server.accept();
			client.setSoTimeout(500);
			new Thread(new ProcessRequest(client)).start();
		}
	}
	/**
	 * 
	 * receive request data and send request data
	 *
	 */
	class ProcessRequest implements Runnable {
		private Socket pClient,socket;
		private InputStream is;
		private OutputStream os;
		private String host=null;
		private int port=80;
		public ProcessRequest(Socket socket){
			this.pClient=socket;
		}
		public void run(){
			try {
				is=pClient.getInputStream();
				byte[] array=new byte[1024];
				int b=is.read(array);
				int count=0;
				StringBuffer sb=new StringBuffer();
				while(b>0){
					for(int i=0;i<b;i++){
					 char c=(char)array[i];
				     if(c=='/'){
				    	 count++;
				     }
				     if(count==2&&c!='/'){
				    	 sb.append(c);
				     }
				     if(count==3){
				    	 break;
				     }
					}
					host=sb.toString();
					break;
				}
				//create new socket link for current 
				System.out.println("当前主机名为:"+host);
				socket=new Socket(host,80);
				socket.setSoTimeout(500);
				//Socket socket=new Socket("127.0.0.1",8087);
				is=pClient.getInputStream();
				os=pClient.getOutputStream();
				OutputStream currentos=socket.getOutputStream();
				InputStream currentis=socket.getInputStream();
				byte[] newarray=new byte[1024];
				int length=0;
				for(int i=0;i<array.length;i++){
					System.out.print((char)array[i]);
				}
				currentos.write(array,0,b);
				//currentos.write(' ');
				//currentos.write(host.getBytes());
				//currentos.write(' ');
				while(b!=-1){
					while((length=currentis.read(newarray))!=-1)	
					 os.write(newarray,0,length);
					 
					 b=is.read(array);
					 currentos.write(array,0,b);
					 
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					socket.close();
					pClient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
}

测试过,性能还可以。代码就不解释了。

猜你喜欢

转载自lqzit.iteye.com/blog/1337144