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

📄 webproxyserver.java

📁 卡耐基梅陇大学SSD8全部练习和考试完全答案
💻 JAVA
字号:
package exam1;

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

public class WebProxyServer {
	private int port=8000;
	private ServerSocket welcomeSocket;
	
	public WebProxyServer()throws IOException{
		welcomeSocket=new ServerSocket(port);
	}
	
	public void service(){
		while(true){
			Socket socket=null;
			try{
				System.out.println("Localhost is listen to you:");
				socket=welcomeSocket.accept();
				
				//create a thread for each request socket
				Thread workThread=new Thread(new Handler(socket,0));
				workThread.start();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	public static void main(String [] argv)throws IOException{
		class RunnableThread1 implements Runnable{
            public void run(){
				Client c=new Client();
				c.sendRequest();
			}
		}
		class RunnableThread2 implements Runnable{
            public void run(){
            	try{
            	WebProxyServer wps=new WebProxyServer();
        		wps.service();
            	}catch(Exception e){
            		e.printStackTrace();
            	}
			}
		}
		Thread t2=new Thread(new RunnableThread2());
		t2.start();
		Thread t1=new Thread(new RunnableThread1());
		t1.start();
		
		
		
	}
	
}
	class Handler implements Runnable {
		private Socket socket;
		private int counter;
		//the constructor
		public Handler(Socket socket,int counter){
			this.socket=socket;
			this.counter=counter;
		}
		//implement the abstract method run
		public void run(){
		
			try{
				 while (true) {  
			BufferedReader inFromKeyBoard=new BufferedReader(
					 new InputStreamReader(System.in));
			DataOutputStream outToClient=new DataOutputStream(socket.getOutputStream());
			 BufferedReader inFromClient = null;  
		      DataInputStream inFromServer = null;  
		      DataOutputStream outToServer = null;
		    String cmd = inFromKeyBoard.readLine();  
	          System.out.println("The Client " + counter  
	              + " request for: " + cmd);  
	  
	          /*  
	           * Process the command from client and identify the method  
	           * and address. If command error, write the error response  
	           * and break.  
	           *   
	           */  
	          StringTokenizer token = new StringTokenizer(cmd);  
	          if (token.countTokens() < 2) {  
	  
	            System.out.println("Command style error!");  
	            outToClient.writeBytes("HTTP/1.1 400 Bad Request\n\r");  
	            break;  
	  
	          } else {  
	  
	            String method = token.nextToken();  
	            String url = token.nextToken();  
	  
	            if (!method.equals("GET")) {  
	              System.out.println("method error!");  
	              System.out.println("HTTP/1.1 400 Bad Request\n\r");  
	              break;  
	            }  
	  
	            if (!url.toUpperCase().startsWith("HTTP://")) {  
	              System.out.println("url error!");  
	              System.out.println("HTTP/1.1 400 Bad Request\n\r");  
	              break;  
	            }  
	  
	            /*  
	             * process the file name and make sure the server name,  
	             * the file path and the number of port.  
	             */  
	            int port = 0;  
	            int strIndex = 0;  
	            String serverName = "";  
	            String portToString = "";  
	            String filePath = "";  
	  
	            url = url.substring(7);  
	            strIndex = url.indexOf("/");  
	            serverName = url.substring(0, url.indexOf("/"));  
	            filePath = url.substring(url.indexOf("/"));  
	  
	            if (serverName.contains(":")) {  
	              strIndex = serverName.indexOf(":");  
	              portToString = serverName.substring(strIndex + 1);  
	              serverName = serverName.substring(0, strIndex);  
	            } else {  
	              portToString = "80";  
	            }  
	  
	            port = Integer.parseInt(portToString);  
	  
	            /*  
	             * Response the right format request. Identify the file  
	             * tpye and write it to the client.  
	             *   
	             */  
	            System.out.println(serverName);  
	            System.out.println(port);  
	            System.out.println(filePath);  
	            System.out.println(url);  
	            System.out.println("Now respond the Client " + counter  
	                + "\'s request...");  
	  
	            /* the client socket */  
	            Socket clientSocket = new Socket(serverName, port);  
	  
	            /* Reader and writer between proxy server and server */  
	            inFromServer = new DataInputStream(clientSocket  
	                .getInputStream());  
	            outToServer = new DataOutputStream(clientSocket  
	                .getOutputStream());  
	  
	            outToServer.writeBytes("GET " + filePath  
	                + " HTTP/1.0\r\n\r\n");  
	  
	            /* read from server and write to client */  
	            String response = inFromServer.readLine();  
	  
	            while (!response.equals("")) {  
	  
	              response = inFromServer.readLine();  
	            }  
	  
	            byte[] bytes = new byte[1024];  
	  
	            int size = 0;  
	  
	            while ((size = inFromServer.read(bytes, 0, 1024)) != -1) {  
	  
	              outToClient.write(bytes, 0, size);  
	            }  
	            break;  
	          }  
	          
				 }
			}catch(Exception e){
				e.printStackTrace();
			}
			//close the socket
			finally{
				try{
					if(socket!=null){socket.close();}
				}catch(Exception e){e.printStackTrace();}
			}
			
		
		
	}
}
	 class Client {
	    //the client socket used to connect to server
		private Socket clientSocket;
		//read the user input from keyboard
		BufferedReader inFromKeyBoard;
		//get the information response by the server
		BufferedReader inFromServer;
		//send the user input to the sever 
		DataOutputStream outToServer;
		public Client(){
			
			this.clientSocket=null;
		}
		
		//connect to the server 
		public void connect(String host,int port){
			try{
				this.clientSocket=new Socket(host,port);
				//read from keyboard
				this.inFromKeyBoard=new BufferedReader
				                   (new InputStreamReader(System.in));
				//read from the client socket
				this.inFromServer=new BufferedReader
				                   (new InputStreamReader(clientSocket.getInputStream()));
				//output to server socket
				this.outToServer=new DataOutputStream
				                   (clientSocket.getOutputStream() );
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		public void close(){
			try{
				//close the socket
				this.clientSocket.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		public  void sendRequest(){
				try{
					connect("localhost",8000);
				//read the user input from keyboard assign to s
				System.out.println("Please input the HTTP request: ");
				String s=inFromKeyBoard.readLine();
				s+="\r\n" + "\r\n";
			
				//send s to server
				outToServer.writeBytes(s);
				
				//get the response header and show to the user
				String file="";
				String temp=file;
				int i=0;
				boolean flag=true;
				for(int j=0; flag&&((j=inFromServer.read())!=-1);){
					switch(j)
		            {
		            case 13: // '\r'
		                break;

		            case 10: // '\n'
		                if(j == i)
		                {
		                    flag = false;
		                } else
		                {
		                    i = j;
		                    file+="\r\n";
		                }
		                break;

		            default:
		                i = j;
		            file+=(char)j;
		                break;
		            }
				}
//				System.out.println("Header:");
//				System.out.println("");
//				System.out.println(file);
				file="";
				temp=inFromServer.readLine();
				//get the response context
				while(temp!=null){
					
					file=file + "\r\n"+temp;
					temp=inFromServer.readLine();
				}
	            // save the response text to a file
				System.out.println("Enter the name of the file to save: ");
				String name=inFromKeyBoard.readLine();
				FileOutputStream filename=new FileOutputStream(name);
				filename.write(file.getBytes());
				filename.flush();
				filename.close();
			
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	

⌨️ 快捷键说明

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