2

I'm trying to implement a simple http server in Java to understand how does a http server work. Now, I'm able to send request from any browser and receive the proper response, however, when I try to simulate a request from Postman, it always throws java.net.SocketException: Broken pipe (Write failed) exception.

My http server is very simple: once received a request, echo a message to sender.

The implementation is as follow, Source Code

package com.ont.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SingleThreadHttpServer implements HttpServer {

    public void run(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        try {
            while (true) {
                Socket socket = serverSocket.accept();

                BufferedReader inBufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                StringBuilder stringBuffer = new StringBuilder();

                String inputLine;
                while ((inputLine = inBufferReader.readLine()) != null && !inputLine.equals("")) {
                    stringBuffer.append(inputLine);
                    stringBuffer.append("\r\n");
                }

                System.out.println(stringBuffer.toString());

                OutputStream outStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new StringReader("A Message from server."));

                // Header should be ended with '\r\n' at each line.
                outStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                outStream.write("Main: OneServer 0.1\r\n".getBytes());
                outStream.write("Content-length: 22\r\n".getBytes()); // if text/plain the length is required
                outStream.write("Content-Type: text/plain\r\n".getBytes());

                // An empty line is required after the header
                outStream.write("\r\n".getBytes());

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    outStream.write(line.getBytes());
                }

                inBufferReader.close();
                bufferedReader.close();
                outStream.flush();
                outStream.close(); // Socket will close automatically once output stream is closed.
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Any types of request sent from Postman will immediately trigger that exception, and debug tells that the socket connection had been lost during outStream.write(...). if I send from a browser, it never trigger that problem.

The thing I don't understand is that there shouldn't be any setting applied to Postman, because when I try to simulate a request to my tomcat, it handles everything like a charm, there must be something gone wrong with my code but I don't know where and why.

Any helps or tips would be appreciated, thank you.

----- Updates ----

From Postman console, I can see this exception,

Error: read ECONNRESET
Request Headers:
accept:"text/plain"
cache-control:"no-cache"

If I left only outStream.write("HTTP/1.1 200 OK\r\n".getBytes()) this line, and delete all other outStream.write..., both browsers and postman work like a charm. this is really pulling my hair, but why?

4
  • Does the postman request say it accepts text/plain? I suspect it doesn't, then it sees the header and closes the request. Oct 15, 2018 at 6:19
  • @BoristheSpider thanks, but I don't think this is the problem, coz postman will accept / if you don't specify its accepts.
    – Saorikido
    Oct 15, 2018 at 9:54
  • 1
    Your HTTP response is missing a Connection: close header to let the client know that the connection will be intentionally closed after the response has been sent. Also, Content-length should be Content-Length. And you didn't indicate which call to outStream.write() is the one throwing the exception. Oct 15, 2018 at 23:42
  • You're right, there's a typo, but I've tried that there is no difference between Content-length and Content-Length, and exception occurs after outStream.write("HTTP/1.1 200 OK\r\n".getBytes()); this call, no matter which kind of orders of other outStream.write(...) to put after this line, it throws the same exception. which means I can only put everything into one single line, and then it closed connection after the first outStream.write() call.
    – Saorikido
    Oct 16, 2018 at 1:46

2 Answers 2

4

I was able to reproduce the issue and identify the root cause of this. Postman connects to the server two times for all localhost URLs. The first connection is just to check the reachability of the server and it is closed immediately without waiting for the response from server. If the server is reachable then it will connect again and send the second request and show the response of the second request.

In case of the server you have posted, it crashes when the first connection from Postman is closed. Since Postman closes the connection without waiting for the full response for the first connection, multiple outStream.write() calls in your server will throw an exception (java.net.SocketException: Broken pipe (Write failed)) causing the server to crash. So the second request sent by Postman will not get any response.

I believe that this is a problem with Postman App which should be fixed. But on the other hand, this type of error should also be properly handled on the server-side to prevent the crash. Not only the Postman App but request sent using other tools can also crash your server if the client destroys the connection in middle of the server sending the response (i.e. make the request using any browser, send a very large response or keep a delay between subsequent outStream.write() calls, close the browser tab before receiving the complete response, this will crash your server).

See the modified server code posted below which will work fine for such situations:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SingleThreadHttpServer implements HttpServer {

    public void run(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        try {
            while (true) {
                Socket socket = serverSocket.accept();

                BufferedReader inBufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                StringBuilder stringBuffer = new StringBuilder();

                String inputLine;
                while ((inputLine = inBufferReader.readLine()) != null && !inputLine.equals("")) {
                    stringBuffer.append(inputLine);
                    stringBuffer.append("\r\n");
                }

                System.out.println(stringBuffer.toString());

                OutputStream outStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new StringReader("A Message from server."));

                try {
                    // Header should be ended with '\r\n' at each line
                    outStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                    //outStream.write("Main: OneServer 0.1\r\n".getBytes());
                    outStream.write("Content-Length: 22\r\n".getBytes()); // if text/plain the length is required
                    outStream.write("Content-Type: text/plain\r\n".getBytes());
                    //outStream.write("Connection: close\r\n".getBytes());

                    // An empty line is required after the header
                    outStream.write("\r\n".getBytes());

                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        outStream.write(line.getBytes());
                    }

                    outStream.flush();
                    outStream.close(); // Socket will close automatically once output stream is closed.
                } catch (SocketException e) {
                    // Handle the case where client closed the connection while server was writing to it
                    socket.close();
                }

                bufferedReader.close();
                inBufferReader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
0

The exception means that the other side already closed the connection while you’re still trying to write to it.

This is just speculation at this point, but possibly Postman doesn’t like the response it’s getting and just gives up. A browser might still accept what you’re doing in a best-effort way but that doesn’t necessarily mean that the response is correct. I don’t know the whole http spec by head so I couldn’t immediately tell you if that is the case. To proceed, perhaps you could look at a tool like Fiddler and see what normally comes back from a http server after a basic request, then see if you’re missing something.

For one, I can see that the content-length is hardcoded, though I wouldn’t expect that to give you that exception.

3
  • Content-length may not be the problem, and I've compared with a normal response which can be properly handled by postman, and changed my response accordingly to this 'normal' response, the exception still happens, as one write anything more than outStream.write("HTTP/1.1 200 OK\r\n".getBytes()); into outStream Broken pipe got happen.
    – Saorikido
    Oct 15, 2018 at 10:24
  • What if you close the inBufferedReader after you write and flush the output? The other side may already have closed the connection. Oct 15, 2018 at 10:29
  • Nothing changed, through debugging the execution never reach the closure part, if only write outStream.write("HTTP/1.1 200 OK\r\n".getBytes()); to outStream then postmen starts to work, seems that the socket connection is broken after this line, donno why.
    – Saorikido
    Oct 15, 2018 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.