Java Reference
In-Depth Information
1. Send the echo string to the server.
2. Block on receive() for up to three seconds, starting over (up to five times) if the reply is
not received before the timeout.
3. Terminate the client.
UDPEchoClientTimeout.java
0 import java.net.*; // for DatagramSocket, DatagramPacket, and InetAddress
1 import java.io.*;
// for IOException
2
3 public class UDPEchoClientTimeout {
4
5
private static final int TIMEOUT = 3000;
// Resend timeout (milliseconds)
6
private static final int MAXTRIES = 5;
// Maximum retransmissions
7
8
public static void main(String[] args) throws IOException {
9
10
if ((args.length < 2) || (args.length > 3)) // Test for correct # of args
11
throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");
12
13
InetAddress serverAddress = InetAddress.getByName(args[0]); // Server address
14
// Convert the argument String to bytes using the default encoding
15
byte[] bytesToSend = args[1].getBytes();
16
17
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
18
19
DatagramSocket socket = new DatagramSocket();
20
21
socket.setSoTimeout(TIMEOUT); // Maximum receive blocking time (milliseconds)
22
23
DatagramPacket sendPacket = new DatagramPacket(bytesToSend, // Sending packet
24
bytesToSend.length, serverAddress, servPort);
25
26
DatagramPacket receivePacket =
// Receiving packet
27
new DatagramPacket(new byte[bytesToSend.length], bytesToSend.length);
28
29
int tries = 0;
// Packets may be lost, so we have to keep trying
30
boolean receivedResponse = false;
31
do {
32
socket.send(sendPacket);
// Send the echo string
33
try {
34
socket.receive(receivePacket); // Attempt echo reply reception
35
36
if (!receivePacket.getAddress().equals(serverAddress)) // Check source
37
throw new IOException("Received packet from an unknown source");
38
39
receivedResponse = true;
 
Search WWH ::




Custom Search