Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you create your socket, first set a timeout:</p> <pre><code>private int timeout = 10000; private int maxTimeout = 25000; clientSocket.setSoTimeout(timeout); </code></pre> <p>With this, if a read times out you'll get <code>java.net.SocketTimeoutException</code> (which you have to catch). Thus, you could do something like this, assuming you've previously set the SO_TIMEOUT as shown above, and assuming that the heartbeat will always get a response from the remote system:</p> <pre><code>volatile long lastReadTime; try { bufferedReader.read(); lastReadTime = System.currentTimeMillis(); } catch (SocketTimeoutException e) { if (!isConnectionAlive()) { logger.info("CONNECTION TERMINATED!"); clientSocket.close(); setUpSocket(); //sets up the server to reconnect to the client } else { sendHeartBeat(); //Send a heartbeat to the client } } public boolean isConnectionAlive() { return System.currentTimeMillis() - lastReadTime &lt; maxTimeout; } </code></pre> <p>A common way of handling this is setting the timeout to some number (say 10 seconds) and then keeping track of the last time you successfully read from the socket. If 2.5 times your timeout have elapsed, then give up on the client and close the socket (thus sending a FIN packet to the other side, just in case).</p> <p>If the heartbeat will <em>not</em> get any response from the remote system, but is just a way of ultimately generating an IOException earlier when the connection has fallen down, then you could do this (assuming that the sendHeartBeat itself will not throw an IOException):</p> <pre><code>try { if (bufferedReader.read() == -1) { logger.info("CONNECTION TERMINATED with EOF!"); resetConnection(); } } catch (SocketTimeoutException e) { // This just means our read timed out ... the socket is still good sendHeartBeat(); //Send a heartbeat to the client } catch (IOException e) { logger.info("CONNECTION TERMINATED with Exception " + e.getMessage()); resetConnection(); } .... private void resetConnection() { clientSocket.close(); setUpSocket(); //sets up the server to reconnect to the client } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload