Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

292
Views
Java, HTTP y sockets: ¿cuándo dejar de leer la solicitud pero mantener el socket abierto?

Mi equipo está construyendo un servidor HTTP básico desde cero en Java, pero nuestros subprocesos de lectura se bloquean una vez que se quedan sin texto de solicitud para leer desde el flujo de entrada del socket. Una serie de puntos exclusivos de nuestra situación que no coinciden con las preguntas formuladas anteriormente :

  • Queremos mantener el socket abierto mientras procesamos la solicitud y generamos una respuesta para devolverla.
  • No analizamos los datos al principio, sino que primero los leemos del zócalo y metemos todo en un archivo de recuperación. Luego comenzamos a analizar y validar desde el archivo, para asegurarnos de no perder la solicitud en caso de desastre.

El código básico:

 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 answers
Answer question

0

readLine() devuelve null solo si "se ha alcanzado el final de la secuencia", es decir, la otra parte ha cerrado el socket. Cuando readLine() lee un salto de línea sin datos anteriores, devuelve una String no nula que tiene una length de 0. Por lo tanto, debe corregir el ciclo while en consecuencia:

 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(); } }

Ver también:

Mientras lee desde el socket, ¿cómo detectar cuándo el cliente ha terminado de enviar la solicitud?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!