Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Implementing a webproxy

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Implementing a webproxy

    HI,,I am currently writting a web proxy in java.The problem that I currently have is that my http response keeps hanging..Can anyone please spot the error in my code.



    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
     
     
     
     
    public class Server  {
    	ServerSocket proxyserver=null;
    	InetSocketAddress adr;
     
    	ClientHandler handler;
    	Socket socket;
     
    	public Server(){
     
    		adr= new InetSocketAddress("localhost",8088);
        	try {
    			proxyserver= new ServerSocket();
    			proxyserver.bind(adr);
    			System.out.println("Serversocket created");
    		} catch (IOException e) {
     
    			e.printStackTrace();
    		}
    	}
    	public static void main(String[] args) {
    		Server server= new Server();
    		server.run();
    	}
     
     
    	public void run() {
     
     
     
    		while(true){
    		try {
    			 System.out.println("Waiting for connection to be made to proxy server");
    			//socket= proxyserver.accept();
     
    			  new Thread( new ClientHandler(proxyserver.accept())).start();  // calls the start method to start a thread which also starts the run method
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		}
     
    	}
    }
     
     
     
    import java.net.*;
    import java.io.*;
     
    public class ClientHandler implements Runnable{
    	Socket socket;
    	Socket serverSocket;
    	private InputStream clientinput;
    	private OutputStream clientoutput;
    	private HttpRequest httprequest;
    	private HttpResponse httpresponse;
    	BufferedWriter toClient;
        BufferedWriter toServer;
     
     
        public ClientHandler(Socket socket){
    		this.socket=socket;
     
     
    		  System.out.println("Accepted a request!\n" + httprequest);
    		  try {
    				this.clientinput=socket.getInputStream();
     
    				this.clientoutput=socket.getOutputStream();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			httprequest= new HttpRequest(clientinput);
    	}
     
    	@Override
    	public void run() {
    		while (true){
    			try{
    			  System.out.println("Accepted a request!\n" + httprequest);
    			  while(httprequest.busy);
    			    URL url = null;
                    try {
                        url = new URL(httprequest.getRequestURL());
                    } catch (MalformedURLException e){
                        try {
    						url = new URL("http:\\"+httprequest.getRequestHost()+httprequest.getRequestURL());
    					} catch (MalformedURLException e1) {
    						// TODO Auto-generated catch block
    						e1.printStackTrace();
    					}
                    }
     
               //     {
                    int remotePort = (url.getPort() == -1) ? 80 : url.getPort();
                    System.out.println("I am going to try to connect to: " + url.getHost() + " at port " + remotePort);
     
    					serverSocket = new Socket(url.getHost(), 80);
    					 System.out.println("Connected to tcd proxy"+ serverSocket.getLocalAddress());
     
     
     
     
                    //write to the server - keep it open.
                    System.out.println("Writing to the server's buffer...");
     
    					toServer = new BufferedWriter(new OutputStreamWriter(serverSocket.getOutputStream()));
     
    					toServer.write(httprequest.getFullRequest());
     
     
    					toServer.flush();
     
                    System.out.println("flushed.");
     
     
     
                    System.out.println("Getting a response...");
     
    					httpresponse = new HttpResponse(serverSocket.getInputStream());
     
                    System.out.println("Got a response!\n" + httpresponse);
                  while(httpresponse.isBusy());   
                  //         }
     
     
                    toClient = new BufferedWriter(new OutputStreamWriter(clientoutput));
     
    					toClient.write(httpresponse.getFullResponse());
    					toClient.flush();
    		            toClient.close();
    		            this.socket.close();
    			}
    			catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
     
     
    		}//while
     
    	}
     
    }
     
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
     
     public class HttpResponse{
            private String fullResponse = "";
            private BufferedReader reader;
            private boolean busy=true; 
        //    private int responseCode;
        //    private CacheControl cacheControl;
     
            public HttpResponse(String input) {
                this(new ByteArrayInputStream(input.getBytes()));
            }
     
            public HttpResponse(InputStream input) {
            	//busy=true;
                reader = new BufferedReader(new InputStreamReader(input));
                try {
                    while (!reader.ready());//wait for initialization.
     
                    String line;
                    while ((line = reader.readLine()) != null) {
                        fullResponse += "\r\n" + line;
     
                  //System.out.println("hellooo  " +fullResponse);
                    }
                    reader.close();
                    fullResponse = "\r\n" + fullResponse.trim() + "\r\n\r\n";
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
                busy = false;
            }
     
     
     
            public String getFullResponse() {
                return fullResponse;
            }
     
            public boolean isBusy() {
                return busy;
            }
     
     
     
            //@Override
            public String toString() {
                return "Response\n==============================\n" + fullResponse;
            }
        }
     
     
     
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
     
     
      /*This class is used to take in a stream which contains a Http request and produce parse valuable information form
        like host name
        url
        The http request would be get request in this case
        */
      public class HttpRequest{
    	 private BufferedReader request; // bufferedreader
    	 String httpfullrequest="";
    	 private String httprequestHost;
         private String httprequestURL;
         public boolean busy=true;
     
     
         public HttpRequest(String input) {
             this(new ByteArrayInputStream(input.getBytes()));
         }
         public HttpRequest( InputStream inputstream){
             request = new BufferedReader(new InputStreamReader(inputstream));
     
             parserequest();
         }
     
         /*
          * This private function parses a request 
          */
         private void parserequest(){
     
               try {
                   while (!request.ready());//wait for buffer not to be empty
     
                   String line;
                   while ((line = request.readLine()) != null) {
                       if(!line.startsWith("Accept-Encoding:")) httpfullrequest += "\r\n" + line;
                       if(line.startsWith("GET ")){httprequestURL=line.split(" ")[1];System.out.println("url \""+httprequestURL+"\"");}
                       if(line.startsWith("Host:")){httprequestHost=line.substring(6);System.out.println("Host \""+httprequestHost+"\"");}
                       if(line.length()==0){System.out.println("empty line");break;}
     
                   }
     
                   httpfullrequest = "\r\n" + httpfullrequest.trim() + "\r\n\r\n";
                 //  request.close();
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
              busy=false;
           }
     
         public boolean isBusy() {
             return busy;
         }
     
         public String getFullRequest() {
             return httpfullrequest;
         }
     
     
         public String getRequestURL() {
             return httprequestURL;
         }
     
     
     
         public String getRequestHost() {
             return httprequestHost;
         }
         //@Override
         public String toString() {
             return "Request\n==============================\n" +httpfullrequest ;
     
         }
     
         }//http request class


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Implementing a webproxy

    Do you have a driver class for executing and testing the program?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Implementing a webproxy

    Quote Originally Posted by Norm View Post
    Do you have a driver class for executing and testing the program?
    The server class Is the driver class.It has a main

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Implementing a webproxy

    What are the steps for testing the code?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Implementing a webproxy

    Quote Originally Posted by Norm View Post
    What are the steps for testing the code?
    Set the proxy to server 8088 in your web browser .Then run the code and type in any url

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Implementing a webproxy

    Try this code for testing:
     
       //  For testing client-server from one class
       public static void main(final String[] args) {    //<<<<<<<<<<<<<<<<<<<
     
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                try{Server.main(args);}catch(Exception x){x.printStackTrace();}
             }
          });
          t1.start();
    /*
          try{Thread.sleep(100);}catch(Exception x){}
     
           Thread t3 = new Thread(new Runnable() {
             public void run() {
                try{Proxy.main(args);}catch(Exception x){x.printStackTrace();}
             }
          });
          t3.start();
    */
          try{Thread.sleep(100);}catch(Exception x){}
     
         Thread t2 = new Thread(new Runnable() {
             public void run() {
                try{Client.main(args); }catch(Exception x){x.printStackTrace();}
             }
          });
          t2.start();
     
          // wait and exit
          try{Thread.sleep(10000);}catch(Exception x){}
          System.out.println("Exiting main");
          System.exit(0);
       }  //  end main()
     
    //-------------------------------------------------------------
    static class Client {
        public static void main(String[] args) throws IOException {
     
            Socket kkSocket = null;
            PrintWriter out = null;
            BufferedReader in = null;
     
            try {
                kkSocket = new Socket("127.0.0.1", 8080);
                out = new PrintWriter(kkSocket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
            out.println("GET http://www.javaprogrammingforums.com/forum.php HTTP/1.1\n"
                         + "Proxy-Connection: keep-alive\n"
                         + "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17\n");
     
            String line = "";
            while ((line = in.readLine()) != null) {
                System.out.println("C - " + line);
            }
            out.close();
            in.close();
            kkSocket.close();
        }
    }
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. implementing KeyListener
    By FARGORE in forum AWT / Java Swing
    Replies: 1
    Last Post: October 18th, 2012, 08:32 AM
  2. Implementing an algorithm
    By me_newbie in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 16th, 2012, 08:50 PM
  3. [SOLVED] need help implementing LinkedList
    By mia_tech in forum What's Wrong With My Code?
    Replies: 14
    Last Post: June 8th, 2012, 11:33 AM
  4. Implementing a 5-heap with an array
    By TBBucs in forum Algorithms & Recursion
    Replies: 0
    Last Post: April 12th, 2010, 10:56 PM
  5. Implementing Semaphores
    By bananasplitkids in forum Threads
    Replies: 1
    Last Post: March 27th, 2010, 04:35 AM

Tags for this Thread