This document is partially blurred.
Unlock all pages and 1 million more documents.
Get Access
Solution for the UDP Lab
The following code presents one solution for the UDP lab. It contains code for the
UDPClient.java and UDPPinger.java classes. The other classes do not require
modifications in the basic lab.
UDPClient.java
/**
/** How many pings to send */
static final int NUM_PINGS = 10;
/** How many reply pings have we received */
int numReplies = 0;
/** Array for holding replies and RTTs */
remoteHost = host;
remotePort = port;
}
/** Main code for pinger client thread. */
public void run() {
/* Create socket. We do not care which local port we use. */
replies[i] = false;
rtt[i] = 1000000;
PingMessage ping = null;
/* Send ping to recipient */
try {
/* Reply did not arrive. Do nothing for now. Figure
* out lost pings later. */
}
}
/* We sent all our pings. Now check if there are still missing
replies. Wait for a reply, if nothing comes, then assume it
was lost. If a reply arrives, keep looking until nothing comes
/* Nothing coming our way apparently. Exit loop. */
numReplies = NUM_PINGS;
}
}
/* Print statistics */
for (int i = 0; i < NUM_PINGS; i++) {
System.out.println("PING " + i + ": " + replies[i] +
rtt[pingNumber] = now.getTime() - then;
numReplies++;
}
/** Main function. Read command line arguments and start the
* client thread. */
public static void main(String args[]) {
System.out.println("Please give port number as integer.");
System.exit(-1);
}
System.out.println("Contacting host " + host + " at port " + port);
UDPClient Client = new UDPClient(host, port);
Client.run();
}
}
UDPPinger.java
/**
* UDPPinger.java -- Basic routines for UDP pinger
/** Create a socket for sending UDP messages */
public void createSocket() {
try {
socket = new DatagramSocket();
public void sendPing(PingMessage ping) {
InetAddress host = ping.getHost();
int port = ping.getPort();
String message = ping.getContents();
try {
throw an exception to indicate that the socket timed out. This
can happen when a message was lost in the network. */
public PingMessage receivePing() throws SocketTimeoutException {
/* Create packet for receiving the reply */
byte recvBuf[] = new byte[MAX_PING_LEN];
reply = new PingMessage(recvPacket.getAddress(),
recvPacket.getPort(),
recvMsg);
} catch (SocketTimeoutException e) {
/* Note: Because the socket has a timeout, we may get a
}
}
Trusted by Thousands of
Students
Here are what students say about us.
Resources
Company
Copyright ©2022 All rights reserved. | CoursePaper is not sponsored or endorsed by any college or university.