javahttp-headerschunked-encodingchunkedtransfer-encoding

How to send a closing chunk in Simple Java Socket Server?


I have a server A that uses Httpcore, HttpcoreNIO for HTTP communications. I have written a Simple Java Socket Server B to use as a backend.

public void run() {
        String expectedResponse = "HTTP/1.0 200 OK\r\nServer: testServer\r\n" +
                                  "Content-Type: text/html\r\n" +
                                  "Transfer-Encoding: chunked\r\n" +
                                  "Transfer-Encoding: chunked\r\n" +
                                  "\r\n" + "<HTML>\n" + "<!DOCTYPE HTML PUBLIC " +
                                  "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" +
                                  "<HEAD>\n" + " <TITLE>Hello World</TITLE>\n" +
                                  "</HEAD>\n" + "\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                                  "<H1 ALIGN=\"CENTER\"> Hello</H1>\n" +
                                  "Sample text 123\n" +
                                  "test 123:\n" + "<PRE>";
        try {
            serverSocket = new ServerSocket(port);
            System.err.println("Server starting on port : " + port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.err.println("Client connected");
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                while (true) {
                    String s;
                    if ((s = in.readLine()) != null) {
                        System.out.println(s);
                        if (!s.isEmpty()) {
                            continue;
                        }
                    }
                    out.write(expectedOutput);
                    System.err.println("connection terminated");
                    out.close();
                    in.close();
                    clientSocket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

When server A receives a response from the backend B, I am getting the following exception.

Premature end of chunk coded message body: closing chunk expected

It seems that Httpcore is expecting a Closing chunk (or Zero-length chunk) before closing the connection.

Can someone let me know how to send this closing chunk from the above Java Simple Socket Server?


Solution

  • Transfer encoding chunked http header means that you are sending the http body in chunks. Each chunk starts with a "header" with the chunk size in bytes, and "/r/n", and then the chunk itself. Once you will do it, and you are done, you should send "0" and "/r/n".

    BTW, is there a reason you are sending the "transfer encoding chunked" http header twice?