Is there a way to read the inputstream for a specific amount of time?

后端 未结 4 1911
清歌不尽
清歌不尽 2021-01-19 18:18

I\'ve a situation where a thread opens a telnet connection to a target m/c and reads the data from a program which spits out the all the data in its buffer. After all the da

相关标签:
4条回答
  • 2021-01-19 18:48

    Generally, no. Input streams don't provide timeout functinality.

    However, in your specific case, that is, reading data from a socket, yes. What you need to do is set the SO_TIMEOUT on your socket to a non-zero value (the timeout you need in millisecs). Any read operations that block for the amount of time specified will throw a SocketTimeoutException.

    Watch out though, as even though your socket connection is still valid after this, continuing to read from it may bring unexpected result, as you've already half consumed your data. The easiest way to handle this is to close the connection but if you keep track of how much you've read already, you can choose to recover and continue reading.

    0 讨论(0)
  • 2021-01-19 18:50

    Use another thread to close the connection after 15 mins. Alternatively, you could check after each read if 15mins have passed and then simply stop reading and cleanup the connection, but this would only work if you're sure the remote server will continue to send data (if it doesn't the read will block indefinitely).

    0 讨论(0)
  • 2021-01-19 19:03

    If the server really dumps data forever, the client will never be blocked in a read operation. You might thus regularly check (between reads) if the current time minus the start time has exceeded your configurable delay, and stop reading if it has.

    If the client can be blocked in a synchronous read, waiting for the server to output something, then you might use a SocketChannel, and start a timer thread that interrupts the main reading thread, or shuts down its input, or closes the channel.

    0 讨论(0)
  • 2021-01-19 19:07

    If you're using a Java Socket for your communication, you should have a look at the setSoTimeout(int) method.

    The read() operation on the socket will block only for the specified time. After that, if no information is received, a java.net.SocketTimeoutException will be raised and if treated correctly, the execution will continue.

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