How do I read a server reply without it blocking me?
<p>I'm writing a proxy and have the following code: </p>

<pre><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); 
}
</code></pre>

<p>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. </p>

<p>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. </p>

<p>How do I make the loop terminate correctly? </p>

<p>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. </p>
