I'm having trouble understanding why the receive call for a UDP connection does not seem to be blocking. Any help would be appreciated.
Basically, the full code is supposed to read and send byte segments of a file over via UDP to another running process listening at a specific port so that that process can then reconstruct (a copy) of the file. In this case however there is no such listener as of yet. The code below only includes the sections which I think the trouble is in.
import java.util.*;
import java.io.*;
import java.nio.*;
import java.net.*;
//... setup code ...
Datagram connection = null;
try {
address = new InetSocketAddress(hostName, portNum); //Assume the hostName and portNum are valid (i.e. localhost, port 8250)
connection = new DatagramSocket(address);
connection.setSoTimeout(100); //This doesn't seem to work, even if I set this to 1000000
} catch (IOException e) {
//Quit
System.out.println(ERROR_UNABLE_TO_CONNECT);
return;
}
//... read contents from sourceFile and create a DatagramPacket for sending first few bytes ...
boolean received = false;
byte[] ackPacketBuffer = new byte[1000];
DatagramPacket ackPacket = new DatagramPacket(ackPacketBuffer, ackPacketBuffer.length);
while(!received) {
try {
connection.send(fileNamePacket); //fileNamePacket can be treated as the packet to be sent
connection.receive(ackPacket); //From my understanding, this should block at least for the set time, before throwing SocketTimeoutException
//... do some checks on the ackPacket, set received flag to be true if successful so that loop is broken...
} catch (SocketTimeoutException e) {
//Packet potentially lost, resend
System.out.println(ERROR_TIMEOUT);
continue;
} catch (IOException e) {
System.out.println(ERROR_SOCKET_WRITE);
continue;
}
}
From what I think should happen, given the scenario for which there is no listener for the specified port, the receive call should block, waiting for an acknowledgement which should never come, until the timeout value has expired, in which case a SocketTimeoutException should be thrown, activating the appropriate catch block and causing an error message to appear on the screen.
Unfortunately I get nothing - placing a print statement after the connection.receive() call shows an infinite loop. The infinite loop is to be expected, but why is it that I'm not getting a thrown SocketTimeoutException?
Other questions which I have encountered so far: