The following code should throw an exception based on whether a timeout was reached:
public boolean isAlive(int workerNum) throws Exception
{
System.out.println("Checking worker #" + workerNum + " from " +
getWorkerAddress(workerNum)
+ " at port " + getWorkerPort(workerNum));
DatagramPacket packet = new DatagramPacket("__ping__".getBytes(), "__ping__".length(),
getWorkerAddress(workerNum), getWorkerPort(workerNum));
socket.setSoTimeout(10000);
try {
System.out.println("Checking worker #" + workerNum);
socket.send(packet);
} catch (SocketTimeoutException e) {
e.printStackTrace();
return false;
}
return true;
}
I've tried in every possible scenario and I can guarantee that the packet is never even thrown as it is never recieved on the other side. Any idea why? Any help is greatly appreciated!
UDP is a connectionless protocol. If you send a packet using UDP you will have no-idea whether the packet was received or not. On the receiving side, if it misses a packet, it will have no idea this happened.
The only way to determine these situations is to build a protocol on top of UDP to handle these situations, though if you are not careful you will be better off just using TCP.
Note: setSoTimeout is a timeout on blocking reads for TCP.
Enable/disable SO_TIMEOUT with the specified timeout, 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. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
it is never recieved on the other side. Any idea why?
If it is not received randomly, you have a networking issue where the packet is being dropped. You can make this happen less often by improving your network, but it will never go away.
If it is never being received, then you have a configuration issue. Either the traffic is not being routed to that host (many organisation control how UDP is passed around their network) or it is being blocked by a firewall, or you have the host and port configured incorrectly. Unlike TCP, you will not get any information as to why this is happening in term of an error message because nothing comes back to the sender.