Is there a way to read an input stream in a specific amount of time?

I have a situation where a thread opens a telnet connection with the target m / c and reads data from a program that spits out all the data in its buffer. After all data has been reset, the target program prints a marker. My thread continues to search for this marker to close the connection (successful read).

Several times the target program does not print any markers, it continues to flush data, and my stream continues to read (the marker is not printed by the target program).

Therefore, I want to read data only for a certain period of time (e.g. 15 minutes / custom). Is there a way to do this at the Java API level?

+4
source share
4 answers

Use a different thread to close the connection after 15 minutes. Alternatively, you can check after each read if 15 minutes have passed and then just stop reading and clearing the connection, but this will only work if you are sure that the remote server will continue to send data (if this is not read indefinitely )

+2
source

Generally not. Input streams do not provide timeout functionality.

However, in your particular case, that is, reading data from the socket, yes. What you need to do is set SO_TIMEOUT on your socket to a non-zero value (timeout in milliseconds). Any read operations that are blocked for the specified time will raise a SocketTimeoutException .

Beware though, even though your socket connection is still valid after that, reading from it may produce unexpected results, since you have already consumed your data halfway. The easiest way to handle this is to close the connection, but if you keep track of how much you have already read, you can restore and continue reading.

+2
source

If you use Java Socket for your communication, you should look at the setSoTimeout (int) method.

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

+2
source

If the server does delete data permanently, the client will never be locked in a read operation. This way you can regularly check (between reads) if the current time minus the start time has exceeded your custom delay and stop reading if there is one.

If the client can be blocked in synchronous reading, waiting for the server to output something, you can use the SocketChannel and start the timer stream, which interrupts the main read stream, or turns off its input, or closes the channel.

0
source

Source: https://habr.com/ru/post/1342100/


All Articles