0

I am implementing a GET request where the client sends a request to the server. The server responds with the correct file-resource, after the client writes on the socket, the server receives it and sends back the header and the file, but the client blocks when using socket.inputStream.

Client:

byte[] requestInBytes=clientRequest.getClientRequest().getBytes();
out.write(requestInBytes);
out.flush();
System.out.println("SENT REQUEST");

in=socket.getInputStream();
byte[]serverResponse=in.readAllBytes();
System.out.println("RECEIVED RESPONSE");

Server:

fileInputStream = Extensions.getFileInputStream(targetURI);
String contentType = Extensions.getContentType(targetURI);
Long contentLength = fileInputStream.getChannel().size();

responseBuilder.append("Date: " + Extensions.getCurrentDate() + "\r\n");
responseBuilder.append("Server: macOS\r\n");
responseBuilder.append("Last-Modified: " + Extensions.getLastModifiedDate(targetURI) + "\r\n");
responseBuilder.append("Content-Length: " + contentLength.toString() + "\r\n");
responseBuilder.append("Content-Type: " + contentType + "\r\n");
responseBuilder.append("Connection: Closed\r\n");

outputStream.write(responseBuilder.toString().getBytes());
outputStream.write(("\r\n").getBytes());
outputStream.write(fileInputStream.readAllBytes());
outputStream.flush();
outputStream.close();
System.out.println("FILE SENT TO CLIENT");
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
amr mahdy
  • 46
  • 4
  • `readAllBytes()` blocks waiting for the end-of-stream, and given your client doesn't shutdown output, the server will block waiting for more data, which never happens. You seem to be implementing HTTP, so it would be better if you use an actual HTTP client (and server), instead of trying to role your own. Otherwise, you need to make proper use of the mechanisms of HTTP (e.g. Content-Length) to determine the number of bytes to read, or otherwise layer a protocol on this so you know how many bytes to expect. – Mark Rotteveel May 13 '22 at 14:06
  • As an aside, you don't show the full server code. – Mark Rotteveel May 13 '22 at 14:15

0 Answers0