Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

289
Vistas
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:

  • We want to keep the socket open while we process the request and produce a response to send back
  • We don't parse the data at first, but rather, we first read it off the socket and chuck the entire thing into a recovery file. Then we begin to parse and validate from the file, to ensure that we don't lose the request in case of disaster.

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();
    }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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?

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda