Scanner.nextLine() blocks when using InputStream from Socket

后端 未结 1 1161
栀梦
栀梦 2021-01-12 08:13

When I receive data using Socket.getInputStream() directly (without some kind of interface like Scanner), it doesn\'t block. But, when I try to use a Scanner (s

1条回答
  •  隐瞒了意图╮
    2021-01-12 08:26

    (I think you've already figured this out but ...)

    The readLine() method returns the rest of the current line. That is, all unconsumed characters up to the next "end of line" sequence, or the "end of stream", which ever comes first. It will block, waiting until the current line (according to the above) is available.

    So if your socket readLine() call blocks, it is waiting for the remote to either send an end-of-line marker (e.g. '\n'), or close its socket output stream (which will result in an "end-of-stream" at this end).

    Q: Why does it "work" when you read from the console?

    A: The console adds an "end-of-line" sequence to the stream whenever you hit ENTER. (Precisely what sequence is added is OS dependent, but the Scanner class will cope with all common varieties, and some unusual ones too.)


    The lesson here is that you should only use Scanner.readLine() if the input stream is line oriented; i.e. if whatever wrote / generated the stream is including "end-of-line" markers.

    0 讨论(0)
提交回复
热议问题