Java Reference
In-Depth Information
40
} catch (InterruptedIOException e) { // We did not get anything
41
tries += 1;
42
System.out.println("Timed out, " + (MAXTRIES − tries) + " more tries...");
43
}
44
} while ((!receivedResponse) && (tries < MAXTRIES));
45
46
if (receivedResponse)
47
System.out.println("Received: " + new String(receivePacket.getData()));
48
else
49
System.out.println("No response −− giving up.");
50
51
socket.close();
52
}
53 }
UDPEchoClientTimeout.java
1. Application setup and parameter parsing: lines 0-17
Convert argument to bytes: line 15
2. UDP socket creation: line 19
This instance of DatagramSocket can send datagrams to any UDP socket. We do not specify
a local address or port so some local address and available port will be selected. We can
explicitly set them with the setLocalAddress() and setLocalPort() methods or in the
constructor.
3. Set the socket timeout: line 21
The timeout for a datagram socket controls the maximum amount of time (milliseconds)
a call to receive() will block. Here we set the timeout to three seconds. Note that timeouts
are not precise: the call may block for more than the specified time (but not less).
4. Create datagram to send: lines 23-24
To create a datagram for sending, we need to specify three things: data, destination
address, and destination port. For the destination address, we may identify the echo
server either by name or IP address. If we specify a name, it is converted to the actual IP
address in the constructor.
5. Create datagram to receive: lines 26-27
To create a datagram for receiving, we only need to specify a byte array to hold the
datagram data. The address and port of the datagram source will be filled in by receive() .
6. Send the datagram: lines 29-44
Since datagrams may be lost, we must be prepared to retransmit the datagram. We loop
sending and attempting a receive of the echo reply up to five times.
Send the datagram: line 32
send() transmits the datagram to the address and port specified in the datagram.
Search WWH ::




Custom Search