Question

I need help with this assignment, please; Programming Assignment 3: UDP Pinger Lab In this lab,...

I need help with this assignment, please;

Programming Assignment 3: UDP Pinger Lab

In this lab, you will study a simple Internet ping server written in the Java language, and implement a corresponding client. The functionality provided by these programs is similar to the standard ping programs available in modern operating systems, except that they use UDP rather than Internet Control Message Protocol (ICMP) to communicate with each other. (Java does not provide a straightforward means to interact with ICMP.)

The ping protocol allows a client machine to send a packet of data to a remote machine, and have the remote machine return the data back to the client unchanged (an action referred to as echoing). Among other uses, the ping protocol allows hosts to determine round-trip times to other machines.

You are given the complete code for the Ping server below. Your job is to write the Ping client.

Server Code

The following code fully implements a ping server. You need to compile and run this code. You should study this code carefully, as it will help you write your Ping client.

import java.io.*; import java.net.*; import java.util.*;

/*
* Server to process ping requests over UDP. */

public class PingServer {

private static final double LOSS_RATE = 0.3;
private static final int AVERAGE_DELAY = 100; // milliseconds

public static void main(String[] args) throws Exception { // Get command line argument. if (args.length != 1) { System.out.println("Required arguments: port");
return; }

int port = Integer.parseInt(args[0]);

// Create random number generator for use in simulating // packet loss and network delay.
Random random = new Random();

// Create a datagram socket for receiving and sending UDP packets // through the port specified on the command line. DatagramSocket socket = new DatagramSocket(port);

// Processing loop. while (true) {

// Create a datagram packet to hold incomming UDP packet. DatagramPacket request = new DatagramPacket(new byte[1024], 1024);

// Block until the host receives a UDP packet. socket.receive(request);

// Print the recieved data. printData(request);

// Decide whether to reply, or simulate packet loss. if (random.nextDouble() < LOSS_RATE) {

System.out.println(" Reply not sent.");

continue; }

// Simulate network delay.
Thread.sleep((int) (random.nextDouble() * 2 * A VERAGE_DELA Y));

// Send reply.
InetAddress clientHost = request.getAddress();
int clientPort = request.getPort();
byte[] buf = request.getData();
DatagramPacket reply = new DatagramPacket(buf, buf.length, clientHost, clientPort); socket.send(reply);

System.out.println(" Reply sent."); }

}

/*
* Print ping data to the standard output stream. */

private static void printData(DatagramPacket request) throws Exception {

// Obtain references to the packet's array of bytes. byte[] buf = request.getData();

// Wrap the bytes in a byte array input stream,
// so that you can read the data as a stream of bytes. ByteArrayInputStream bais = new ByteArrayInputStream(buf);

// Wrap the byte array output stream in an input stream reader, // so you can read the data as a stream of characters. InputStreamReader isr = new InputStreamReader(bais);

// Wrap the input stream reader in a bufferred reader,
// so you can read the character data a line at a time.
// (A line is a sequence of chars terminated by any combination of \r and \n.) BufferedReader br = new BufferedReader(isr);

// The message data is contained in a single line, so read this line. String line = br.readLine(); // Print host address and data received from it. System.out.println(

"Received from " + request.getAddress().getHostAddress() + ": " +
new String(line) );

}}

The server sits in an infinite loop listening for incoming UDP packets. When a packet comes in, the server simply sends the encapsulated data back to the client.

Packet Loss

UDP provides applications with an unreliable transport service, because messages may get lost in the network due to router queue overflows or other reasons. In contrast, TCP provides applications with a reliable transport service and takes care of any lost packets by retransmitting them until they are successfully received. Applications using UDP for communication must therefore implement any reliability they need separately in the application level (each application can implement a different policy, according to its specific needs).

Because packet loss is rare or even non-existent in typical campus networks, the server in this lab injects artificial loss to simulate the effects of network packet loss. The server has a parameter LOSS_RATE that determines which percentage of packets should be lost.

The server also has another parameter AVERAGE_DELAY that is used to simulate transmission delay from sending a packet across the Internet. You should set AVERAGE_DELAY to a positive value when testing your client and server on the same machine, or when machines are close by on the network. You can set AVERAGE_DELAY to 0 to find out the true round trip times of your packets.

Compiling and Running Server

To compile the server, do the following:

javac PingServer.java

To run the server, do the following:

   java PingServer port

where port is the port number the server listens on. Remember that you have to pick a port number greater than 1024, because only processes running with root (administrator) privilege

can bind to ports less than 1024.

Note: if you get a class not found error when running the above command, then you may need to tell Java to look in the current directory in order to resolve class references. In this case, the commands will be as follows:

java -classpath . PingServer port

Your Job: The Client

You should write the client so that it sends 10 ping requests to the server, separated by approximately one second. Each message contains a payload of data that includes the keyword PING, a sequence number, and a timestamp. After sending each packet, the client waits up to one second to receive a reply. If one seconds goes by without a reply from the server, then the client assumes that its packet or the server's reply packet has been lost in the network.

Hint: Cut and paste PingServer, rename the code PingClient, and then modify the code.

You should write the client so that it starts with the following command:

   java PingClient host port

where host is the name of the computer the server is running on and port is the port number it is listening to. Note that you can run the client and server either on different machines or on the same machine.

The client should send 10 pings to the server. Because UDP is an unreliable protocol, some of the packets sent to the server may be lost, or some of the packets sent from server to client may be lost. For this reason, the client cannot wait indefinitely for a reply to a ping message. You should have the client wait up to one second for a reply; if no reply is received, then the client should assume that the packet was lost during transmission across the network. You will need to research the API for DatagramSocket to find out how to set the timeout value on a datagram socket.

Your client will display the reply message from the server along with the RTT for each datagram received or a message indicating lost packet for those not returned within the time limit.

When developing your code, you should run the ping server on your machine, and test your

client by sending packets to localhost (or, 127.0.0.1). After you have fully debugged your code, you should see how your application communicates across the network with a ping server run by another member of the class.

Message Format

The ping messages in this lab are formatted in a simple way. Each message contains a sequence of characters terminated by a carriage return character (r) and a line feed character (n). The message contains the following string:

PING sequence_number time CRLF

where sequence_number starts at 0 and progresses to 9 for each successive ping message sent by the client, time is the time when the client sent the message, and CRLF represents the carriage return and line feed characters that terminate the line.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

First Let me paste Server and Client program later will explain how it works.

PingServer.java

=============

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;

public class PingServer {
private static final double LOSS_RATE = 0.3;
private static final int AVERAGE_DELAY = 100;

public static void main(String[] args) throws Exception {

if (args.length != 1) {
System.out.println("Required arguments: port");
return;
}

int port = Integer.parseInt(args[0]); // Port number.On which port you want to run your server for example 9999.

Random random = new Random();
DatagramSocket socket = new DatagramSocket(port);
while (true) {
DatagramPacket request = new DatagramPacket(new byte[1024], 1024);

socket.receive(request);
printData(request);
if (random.nextDouble() < LOSS_RATE) {
System.out.println(" Reply not sent.");
continue;
}
Thread.sleep((int) (random.nextDouble() * 2 * AVERAGE_DELAY));
InetAddress clientHost = request.getAddress();
int clientPort = request.getPort();
byte[] buf = request.getData();
DatagramPacket reply = new DatagramPacket(buf, buf.length, clientHost, clientPort);
socket.send(reply);
System.out.println(" Reply sent.");
}
}

private static void printData(DatagramPacket request) throws Exception {
byte[] buf = request.getData();
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
InputStreamReader isr = new InputStreamReader(bais);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
System.out.println("Received from " + request.getAddress().getHostAddress() + ": " + new String(line));
}
}

PingClient.java

============

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

public class PingClient {
public static void main(String[] args) {

if (args.length < 2) {
System.out.println("Syntax: QuoteClient <hostname> <port>");
return;
}

String hostname = args[0]; // Need to pass as an argument at position zero. Which should be server
// hostname. In our case we are running both server and client on same machine,
// so host name will be 127.0.0.1

int port = Integer.parseInt(args[1]); // Port number. On which port server application is running for example
// 9999.

try {
InetAddress address = InetAddress.getByName(hostname);
DatagramSocket socket = new DatagramSocket();

while (true) {
String welcome = "Welcome to JAVA!";
DatagramPacket request = new DatagramPacket(welcome.getBytes(), welcome.length(), address, port);
socket.send(request);

byte[] buffer = new byte[512];
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);

String quote = new String(buffer, 0, response.getLength());

System.out.println(quote);
System.out.println();

Thread.sleep(10000);
}

} catch (SocketTimeoutException ex) {
System.out.println("Timeout error: " + ex.getMessage());
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Client error: " + ex.getMessage());
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

Server output

==========

For testing purpose I have hard coded port number to 9999. But it should come from command line argument when you run server program from command line.

BS 7 - prer X dition-client dition-server PingServer.java X PingClient.java 5 import java.io.InputStreamReader; 6 import java

Client output

==========

In the code below I have hard coded server host name and port number. But both should come from command line argument when you run client application which I will explained below.

- PingServer.java O PingClient.java X client cerver 9 public class Pingclient { 100 public static void main(String[] args) {

First You need to create two java files one for PrintServer.java and put server code in it as well as PrintClient.java and put client code in it.

compile both java files and run the server program first, because first server needs to be running to make requests to it.

Run below command in the terminal or command prompt to run server program.

java PrintServer 9999

In the above command 9999 is port number, which means we are saying our server needs to be run on port 9999.

Now run client by running below command in new terminal or command prompt

java PrintClient 127.0.0.1 9999

In the above command 127.0.0.1 is hostname. On which host server is running to make requeset.

9999 is port number on which port server is running.

Now you can observe the results printed on server terminal as well as on client terminal.

How it works?

We have written small server program which uses java.net API to work with sockets (Sockets allow you to exchange information between processes on the same machine or across a network) and packets (packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network).

Once we run server program which will keep on running forever for requests until we kill it.

Client program simply makes request (using same java.net API) to server with server host name and port number along with data which clients want to send. Once server receives request it processes and sends response back to client.

Add a comment
Know the answer?
Add Answer to:
I need help with this assignment, please; Programming Assignment 3: UDP Pinger Lab In this lab,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The following Client side Java code can send a message to the server side via UDP...

    The following Client side Java code can send a message to the server side via UDP socket. The client side Java code and the server side Java code are running in two different hosts respectively. The server side host name is “MyFileServer”. The server side receives the message and converts all the letters in the message received to uppercase, then sends the modified message back to the client side. Please read the code carefully, and fill out the blanks with...

  • Using python 3 to create the UDP Ping Clien and server. Using UDP sockets, you will...

    Using python 3 to create the UDP Ping Clien and server. Using UDP sockets, you will write a client and server program that enables the client to determine the round-trip time (RTT) to the server. To determine the RTT delay, the client records the time on sending a ping request to the server, and then records the time on receiving a ping response from the server. The difference in the two times is the RTT. The ping message contains 2...

  • Q7 The following Client side Java code can send a message to the server side via...

    Q7 The following Client side Java code can send a message to the server side via UDP socket. The client side Java code and the server side Java code are running in two different hosts respectively. The server side host name is “MyFileServer”. The server side receives the message and converts all the letters in the message received to uppercase, then sends the modified message back to the client side. Please read the code carefully, and fill out the blanks...

  • Overview UDP is a transport layer protocol that provides no reliability. This project aims to show...

    Overview UDP is a transport layer protocol that provides no reliability. This project aims to show how to implement extra features for the protocol in the application layer. The project will develop a new version of UDP protocol called UDPplus which provides reliable connection oriented between a client and a UDPplus sever. The UDPplus is implemented at application layer using UDP protocol only. Basic Scenario The UPDplus is a simple bank inquiry application where the client sends full name and...

  • Practice socket programming with threads: Write an 'echo' server using UDP. (This server does not need...

    Practice socket programming with threads: Write an 'echo' server using UDP. (This server does not need to be multi-threaded, but make sure that you do know how to implement a multi-threaded server when asked.) Each request is handled by replying to the client with the unmodified string the client sent. Also, write an 'echo' client to test your server. Each client will send 20 sequentially numbered messages to the server & receive the replies. This code needs to be in...

  • *****Can someone please HELP me with this assignment please, I am struggling with this assignment and...

    *****Can someone please HELP me with this assignment please, I am struggling with this assignment and would appreciate some help, needs to be done in c/c++ ******* (100 marks) In this problem, you will write a file transfer program for transferring files between two computers connected by a network. The protocol that you will implement is called the Simple File Transfer Protocol (SFTP). The complete description for SFTP is given below. PART 1 SFTP is a simple protocol for transferring...

  • implement the follwing code using command promp or Eclipse or any other program you are familiar with. keep the name of...

    implement the follwing code using command promp or Eclipse or any other program you are familiar with. keep the name of the classes exatcly the same as requested for testing purpose. please follow each instruction provided below Objective of this assignment o get you famililar with developing and implementing TCP or UDP sockets. What you need to do: I. Implement a simple TCP Client-Server application 2. and analyze round trip time measurements for each of the above applications 3. The...

  • You can refer chapter 2 and chapter 3 of Computer Networking: A Top-Down approach by Kurose...

    You can refer chapter 2 and chapter 3 of Computer Networking: A Top-Down approach by Kurose and Ross for the following labs. Please read the instructions below for submissions. Upload the shared pcap file (Homework5.pacp) into wireshark. HTTP In this lab, we’ll explore several aspects of the HTTP protocol. Capture packets and filter for http protocol and answer the following questions. (Hint: Apply http filer) What version of HTTP version(1.0 or 1.1) is client running and what is the version...

  • PLEASE HELP WITH THESE COMPUTER NETWORK QUESTIONS THESE INCLUDE MCQS AND CALCULATIONS With reference to the...

    PLEASE HELP WITH THESE COMPUTER NETWORK QUESTIONS THESE INCLUDE MCQS AND CALCULATIONS With reference to the Go-Back-N and Selective repeat protocols, what does the window value signify? The packets that have already been ACKed The packets sent but remain unACKed The sequence numbers available and not yet sent The sequence numbers of packets not yet available None of the above 1 points    QUESTION 2 Which of the following is NOT a component of the TCP congestion control algorithm? Slow...

  • I need help with my IM (instant messaging) java program, I created the Server, Client, and...

    I need help with my IM (instant messaging) java program, I created the Server, Client, and Message class. I somehow can't get both the server and client to message to each other. I am at a roadblock. Here is the question below. Create an IM (instant messaging) java program so that client and server communicate via serialized objects (e.g. of type Message). Each Message object encapsulates the name of the sender and the response typed by the sender. You may...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT