I get this error all the time tried everything switching JVMs and stuff changing code itself but nothing really works Chat GPT also doesn't help. If someone know what's the dead with this please help. I really want to understand what's wrong with it.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpServer {
private final int port;
public HttpServer(final int port) {
this.port = port;
}
public void run() {
try(var serverSocket = new ServerSocket(port)) {
var socket = serverSocket.accept();
System.out.println("Socket accepted");
processSocket(socket);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void processSocket(Socket socket) throws IOException {
try(socket;
var inputStream = new DataInputStream(socket.getInputStream());
var outputStream = new DataOutputStream(socket.getOutputStream())) {
System.out.println(new String(inputStream.readNBytes(100)));
byte[] body = Files.readAllBytes(Path.of("src/main/resources/example.html"));
outputStream.write("""
HTTP/1.1 200 OK
content-type: text/html
content-length: %s
""".formatted(body.length).getBytes());
outputStream.write(System.lineSeparator().getBytes());
outputStream.write(body);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.util.concurrent.ExecutionException;
import static java.net.http.HttpRequest.BodyPublishers.ofFile;
public class HttpClientRunner {
public static void main(final String[] args) throws IOException, InterruptedException, ExecutionException {
var httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8082"))
.header("content-type", "application/json")
.POST(ofFile(Path.of("src/main/resources/example.json")))
.build();
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.headers());
System.out.println(response.body());
}
}
Tried to search everywhere but found literally nothing.
readNBytesmight block. But you don't explain where your code is deviating from your expectations, so all we can do is guess.