Note that there are some explanatory texts on larger screens.

plurals
  1. POAccurately detecting socket sending failures in Java
    primarykey
    data
    text
    <p>I am writing an Android app that initializes a <code>DatagramSocket</code> to connect to a server and then uses an infinite loop to periodically (e.g. every 5 seconds) send packets of data. The sending code is below:</p> <pre><code>DatagramPacket packet = new DatagramPacket(message, message.length); try { socket.send(packet); } catch (IOException e) { // Log failure and return } // Log success </code></pre> <p>Now, I can afford to lose a packet every once in a while. But I would like to be able to detect if the server becomes unavailable (e.g. crashes) while I am connected, in which case I would like to hold on to the messages I send (to send them at another time). Originally I thought that an exception will be thrown every time I try to send a packet through this socket, and hence would be able to deal with storing the messages in my <code>catch</code> block. In fact it partially works. I model server crashes by just switching off the server, and I start getting exceptions with message <code>sendto failed: ECONNREFUSED (Connection refused)</code> when I send a packet. The problem is, not every attempt to send throws an exception, but only every even attempt - so my log looks like</p> <blockquote> <p>Success, Error, Success, Error, ...</p> </blockquote> <p>What happens in my understanding is that on the first attempt to send a packet after the server becomes unavailable, the packet gets sent, the socket doesn't wait to see if there is an error message, and a success is logged. Then on the next attempt, the socket tries to send a packet, sees the previous error message, and throws an exception without sending the packet, hence leading to an error being logged. However, because the packet was not sent, there will be again no exception thrown on the subsequent attempt to send a packet. This is a hypothesis I drew after seeing my log, so I could be mistaken in my reasoning here.</p> <p>My question is, is there any way to make sure the exception is thrown every time as long as the server is unavailable? Or is there any other way to detect that the other end of the socket has silently disconnected? I tried checking for <code>socket.isConnected()</code> inside my loop, but it always returns <code>true</code>.</p>
    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.
 

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