MDjava
MDjava

Reputation: 113

Java, HTTP, & Sockets: When to stop reading the request but keep the socket open?

My team is building a basic HTTP server from scratch in Java, but our reader threads block once they run out of request text to read from the socket's input stream. A number of points unique to our situation that don't match up with questions asked previously:

The basic code:

public void readSocket() {
    receivedTime = System.currentTimeMillis();
    requestFile = new File("recovery/" + receivedTime + ".txt");
    try(
        FileWriter fw = new FileWriter(requestFile);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter out = new BufferedWriter(fw); 
    )
    {
        String line;
        while((line = in.readLine()) != null){ //TODO: this is where it blocks after reading past the last line of the request. 
            out.write(line);

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

Upvotes: 1

Views: 1913

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597036

readLine() returns null only if "the end of the stream has been reached", ie the socket has been closed by the other party. When readLine() reads a line break with no preceding data, it returns a non-null String that has a length of 0. So you need to fix you while loop accordingly:

public void readSocket() {
    receivedTime = System.currentTimeMillis();
    requestFile = new File("recovery/" + receivedTime + ".txt");
    try(
        FileWriter fw = new FileWriter(requestFile);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter out = new BufferedWriter(fw); 
    )
    {
        String line;

        // read request headers...
        do {
            line = in.readLine();

            if (line == null) return; // socket closed

            out.write(line);
            out.NewLine();
            out.flush();

            if (line.isEmpty()) break; // end of headers reached

            // process line as needed...
        }
        while (true);

        // check received headers for presence of a message
        // body, and read it if needed. Refer to RFC 2616
        // Section 4.4 for details...

        // process request as needed...

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

Also see:

While reading from socket how to detect when the client is done sending the request?

Upvotes: 1

Related Questions