1

我有这个任务,我应该编写一个代理服务器,它使用 java 套接字来处理来自客户端的获取请求。我现在被困住了,一直在谷歌上寻找答案,但没有成功。

Christoffers 解决方案帮助我解决了我的第一个问题。现在我已经更新了代码,这就是我正在使用的。

问题是它在将数据包发送回客户端循环之前只下载了大多数网页的一部分。目前我无法解释为什么它的行为方式是这样的。

public class MyProxyServer {  
    //Set the portnumber to open socket on
    public static final int portNumber = 5555;  

    public static void main(String[] args){  
//create and start the proxy
MyProxyServer myProxyServer = new MyProxyServer();  
myProxyServer.start();  
}  
public void start(){  
System.out.println("Starting MyProxyServer ...");  
try {  
    //create the socket 
    ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber);  

    while(true)
    {    
        //wait for a client to connect
        Socket clientSocket = serverSocket.accept();  

        //create a reader to read the instream
        BufferedReader inreader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));  

        //string builder for preformance when we loop over the inputstream and read lines
        StringBuilder builder = new StringBuilder();
        String host = "";


        for (String buffer; (buffer = inreader.readLine()) != null;) {
        if (buffer.isEmpty()) break;
        builder.append(buffer.replaceAll("keep-alive", "close"));
        if(buffer.contains("Host"))
            {
            //parse the host
            host = buffer.replaceAll("Host: ", "");
            }
        System.out.println(buffer);
        }


        String req = builder.toString();
        System.out.println("finshed reading \n" + req);
        System.out.println("host: " + host);


        //new socket to send the information over
        Socket s = new Socket(InetAddress.getByName(host), 80);

        //printwriter to send text over the output stream
        PrintWriter pw = new PrintWriter(s.getOutputStream()); 

        //send the request from the client
        pw.println(req+"\r\n");
        pw.flush();

        //create inputstream to receive the web page from the host
        BufferedInputStream in = new BufferedInputStream(s.getInputStream());

        //create outputstream to send the web page to the client
        BufferedOutputStream outbuffer = new BufferedOutputStream(clientSocket.getOutputStream());

        byte[] bytebuffer = new byte[1024];
        int bytesread;

        //send the response back to the client
        while((bytesread = in.read(bytebuffer)) != -1) {
        System.out.println(bytesread);
        outbuffer.write(bytebuffer,0, bytesread);
        outbuffer.flush();
        }
        System.out.println("done sending");

        //close the streams
        inreader.close();
        s.close();
        pw.close();
        outbuffer.close();
        in.close();
    }


} catch (IOException e) {  
    e.printStackTrace();
}  catch(RuntimeException e){
    e.printStackTrace();
}
}  

}

如果有人能向我解释为什么我不能让它正常工作以及如何解决它,我将非常感激!

提前致谢。

4

0 回答 0