0

I have Socket stream and I need to use in.read() from stream function even if no data available.

I need this approach because blocking read function raises exception if the socket is disconnected and this is the only way to know if socket is alive.

I found that in.read() is waiting for data for approximately 2 min. and raises SocketTimeoutException if no data is available.

Can I somehow set read from socket timeout value?

The Roy
  • 2,178
  • 1
  • 17
  • 33
vico
  • 17,051
  • 45
  • 159
  • 315
  • see http://stackoverflow.com/questions/4969760/set-timeout-for-socket – Exceptyon Apr 19 '16 at 10:29
  • The following statements in your question are mistaken: (1) 'blocking `read()` function raises exception if the socket is disconnected', and (2) '`in.read()` is waiting for approximately 2 min`. The fact is that a blocking mode read blocks forever unless (1) the connection has been reset, (2) the peer has disconnected or (3) you have set a read timeout. 'Can I somehow set read from socket timeout value?' is meaningless. Unclear what you're asking. – user207421 Apr 19 '16 at 11:24

2 Answers2

-1

You could use the Socket's KeepAlive() function as follows:

s = new Socket(serverIP, portOut);
s.setKeepAlive(true);

This will cause the socket to (obviously) keep itself alive and will not timeout.

You can also increase the timeout parameter by:

s.setSoTimeout(time_in_milliseconds);
Tomer Something
  • 770
  • 1
  • 10
  • 24
  • Untrue. If the peer doesn't send anything within the read timeout period, the read will timeout, keepalive or no keepalive. – user207421 Apr 19 '16 at 11:25
-1

Just set the SO_TIMEOUT on your Java Socket using:

socket.setSoTimeout(30*1000);

Timeout above is set in milliseconds

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. On Expiry, SocketTimeoutException is raised.

The Roy
  • 2,178
  • 1
  • 17
  • 33
  • That is his *problem.* Not the solution. – user207421 Apr 19 '16 at 11:25
  • Well his question ends with how to set timeout on sockets for read operation? This response is correct to that extent. But if you are suggesting why he is getting exception while blocking to read. That is a different problem. He needs to check if it is due to read returning less than 0 (error) or 0 bytes hinting the connection is reset by peer. – The Roy Apr 19 '16 at 11:30
  • The question reports a problem with unexpected socket timeouts. The reason can only be that he is already setting a read timeout. If he wasn't, there wiould be no timeout: the read would block forever. `read()` can't return < 0 or zero *and* throw an exception at the same time, and zero does not 'hint that the connection has been reset' by anybody, including the peer. – user207421 Apr 19 '16 at 11:37
  • That makes sense. Agreed. – The Roy Apr 19 '16 at 11:50