开发者

How do I read a server reply without it blocking me?

I'm writing a proxy and have开发者_JS百科 the following code:

Socket conUser;
Socket conDest;
try{
    ServerSocket ss = new ServerSocket(Integer.parseInt(p.getProperty("proxy.port")));
    while(true){
        //Connect to user
        conUser = ss.accept();
        BufferedReader inputFromUser = new BufferedReader(new InputStreamReader(conUser.getInputStream()));
        BufferedWriter outputToUser = new BufferedWriter(new OutputStreamWriter(conUser.getOutputStream(), "UTF8"));

        //Get user request
        StringBuffer req = new StringBuffer();
        getUserRequest(inputFromUser, req);
        System.out.println("User requested the following:");
        System.out.println(req);

        //Connect to server
        InetAddress a = InetAddress.getByName(determineHost(req));
        conDest = new Socket(a,80);

        //Send request to server
        BufferedWriter outputToServer = new BufferedWriter(new OutputStreamWriter(conDest.getOutputStream(), "UTF8"));
        InputStreamReader inputFromServer = new InputStreamReader(conDest.getInputStream(), "UTF8");
        outputToServer.write(req.toString());
        outputToServer.flush();

        System.out.println("==============================");
        System.out.println("Server replied with the following:");
        //Read reply from the server
        //=========================================
        int chars;
                while ((chars = inputFromServer.read()) != -1) {
                    System.out.print((char)chars);
                    outputToUser.write(chars);
                    outputToUser.flush();
                    //serverReply.append(chars);
              }
               //Relay reply to user
             //outputToUser.write(serverReply.toString());
             //System.out.println(serverReply);
             //outputToUser.flush();
        conUser.close();
        conDest.close();
    }
} 
catch (Exception e) {
      System.err.println(e); 
}

What happens is: I make a connection and it succeeds. I also send the request, and that succeeds too. I also get a reply, and am able to load the entire page's HTML, except that the read doesn't seem to terminate when it reaches the end of the content.

Specifically, I was attempting to load Google's homepage and the chunked transfer reached 0 (that is- end of chanked transfer), and thus there should've been no more input to read, but this did not cause the loop to stop reading. What's also strange to me is that pretty much all code examples of proxies do use this loop, and assuming they work, I don't see much differences between their code and mine.

How do I make the loop terminate correctly?

EDIT: for the record, yes- I know that the TCP connection should be kept open to handle further connections. This is not relevant to the problem I'm having. I need to get this loop to terminate per response.


In general the connection is not closed at the end of each response. Creating TCP connections is relatively time-consuming so the connection is left open, ready for you to send your next request.

Here are a couple of explanatory links:

  • http://en.wikipedia.org/wiki/HTTP_persistent_connection

  • http://en.wikipedia.org/wiki/HTTP_pipelining


If you want to terminate connection correctly after receiving HTTP response, your simple loop is not enough. You have to determine the end of message as described in section 4.4 Message Length of RFC 2616 and then close the connection.

However, it would be better to use existing libraries, such as built-in URLConnection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜