Java Socket - how does the read() method know if the end of stream has been reached?

2k views Asked by At
  1. How does the InputStream.read(byte[]) method know if the "End of Stream" has been reached and return "-1" ?

  2. What are all the conditions for returning "-1" ?

  3. How to detect an "End of Stream" (without sending an integer which contains the total number of bytes to read before) ?

Example of use:

InputStream input = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for(int size = -1; (size = input.read(buffer)) != -1; ) {
    baos.write(buffer, 0, size);
}
2

There are 2 answers

1
Louis Wasserman On

InputStream is an abstract type with many implementations. A FileInputStream, for example, will return -1 if you have reached the end of the file. If it's a TCP socket, it will return -1 if the connection has been closed. It is implementation-dependent how end-of-stream is determined.

5
Janardhan B. Chinta On

It does not.

When you try to read n bytes from socket, the call may return before n bytes are ready, and number of bytes read is returned. How does read() decide to return? Based on timeout. The timeout value is commented as SO_TIMEOUT in AbstractPlainSocketImpl.java. Actually, real read happens with the native code, probably written in C, the SO_TIMEOUT defaults to whatever native code has. However, you can set timeout value with Socket.setSocketTimeout(millis).

SocketInputStream.java

        n = socketRead(fd, b, off, length, timeout);
        if (n > 0) {
            return n;
        }

If you observe HTTP protocol, the client and server coordinate using the content-length header to indicate each other when a request and response is ending, and when a new request and response is starting. The order of bytes received is taken care by the TCP layer.

Socket stream does not have end of stream check, like feof check with files. Its a two way communication read and write. However, you can check if bytes are available to read. TCP connections are live until either client or server chooses to close.