Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discarding input from socket

From Socket documentation:

shutdownInput

public void shutdownInput()
                   throws IOException

Places the input stream for this socket at "end of stream". Any data sent to the input stream side of the socket is acknowledged and then silently discarded.

If you read from a socket input stream after invoking shutdownInput() on the socket, the stream will return EOF.

In order to test interaction between clients in a server, I've written some client bots. These bots generate somewhat random client requests. Since these only write to the server, they have no need for the input stream, they do not need to read the updates the server sends. This is the main body of code for the bots:

private void runWriteBot(PrintWriter out) throws IOException {
    //socket.shutdownInput();
    String request;
    System.out.println("Write bot ready.");
    while (!quit) {
        request = randomRequest();
        out.println(request);
        sleep();
    }
}

If I uncomment the shutdownInput, an exception is thrown in the server's client handler:

Connection reset

I wasn't expecting an exception to be thrown on the other side of the socket. The documentation suggests (to me, at least) that anything sent by the other side will just be silently discarded, causing no interference with the other end's activity, ie without having the other side throw an exception.

  1. Can I just ignore what the server sends, or should I drain what comes to the input stream?

  2. Is there any automagic way of doing it, or do I need to regularly read and ignore?

like image 685
afsantos Avatar asked Oct 05 '13 18:10

afsantos


1 Answers

The behaviour when you call shutdownInput() is platform-dependent.

  1. BSD Unix will silently discard any further input.
  2. Linux will keep buffering the input, which will eventually block the sender, or cause him to get EAGAIN/EWOULDBLOCK if he is in non-blocking mode.
  3. Windows will reset the connection if any further data arrives.

This is determined by the platform, not by Java.

I don't see any need for calling shutdownInput() in most situations. The only thing it is really useful for is unblocking a read. In your situation you are going to have to read the server responses.

like image 102
user207421 Avatar answered Sep 30 '22 16:09

user207421