Discarding input from socket

一个人想着一个人 提交于 2020-01-21 07:35:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19201451/discarding-input-from-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!