Lab Manual for AdvanceComputer Programming
Lab-13
Socket Programming using UDP Protocol
Lab 13: Socket Programming using UDP Protocol
Table of Contents
1 Introduction 137
2 Activity Time boxing 137
3 Objective of the experiment 138
4 Concept Map 138
4.1 Client Server Program 138
4.2 IP Address 138
4.3 Ports 138
4.4 Host Names 138
4.5 Loopback address 139
4.6 InetAddress class 139
5 Homework before Lab 139
5.1 Problem Solution Modeling 139
5.1.1 Problem description: 140
5.2 Practices from home 140
5.2.1 Task-1 140
6 Procedure& Tools 140
6.1 Tools 140
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 140
6.2.1 Compile a Program 140
6.2.2 Run a Program 140
6.3 Walkthrough Task [Expected time = 30mins] 140
6.3.1 Implementation of UDP Server 140
6.3.2 Implementation of UDP Client 142
7 Practice Tasks 143
7.1 Practice Task 1 [Expected time = 20mins] 143
7.2 Practice Task 2 [Expected time = 20mins] 143
7.3 Practice Task 3 [Expected time = 20mins] 143
7.4 Practice Task 4 [Expected time = 20mins] 144
7.5 Out comes 144
7.6 Testing 144
8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks] 145
9 Evaluation criteria 145
10 Further Reading 145
10.1 Books 145
10.2 Slides 145
Department of Computer Science, Page 136
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
Lab 13: Socket Programming using UDP Protocol
1 Introduction
Network Programming is very important to establish communication between two systems on
the network. All the resources and services cannot be deployed on a single system. Therefore, it
is understandable that we need to distribute the load between multiple systems. Network
programming is the basis for distributed computing. Basically two main protocols are used to
establish communication on the network.
1. User Datagram Protocol
2. Transmission Control Protocol
In this lab we are going to implement a User Datagram Protocol which is commonly known as
UDP. The TCP protocol will be studied in the next Lab.
UDP is a connection less protocol which means that to send and receive data connection is not
established. The data in UDP protocol is converted into packets then individual packets travel on
the network till they reach the destination. The UDP protocol is unreliable; which means that if a
packet is lost then it is gone for good, it won’t be retransmitted again.
UDP protocol is used in situations where the real-time communication is required. For example
in a CCTV camera setup the real-time communication is important therefore UDP protocol is
used. UDP based communication is comparatively fast as it does not generate acknowledgements
of the received packets.
Your task in this lab will be to implement the UDP protocol and test it.
Relevant Lecture Material
a) Revise Lecture No. 21 and 22
b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 978-1026
2. Revise the OSI Model.
2 Activity Time boxing
Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-up Path for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 20mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins
Department of Computer Science, Page 137
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
3 Objective of the experiment
To understand network related terms: IP Address, Ports, Host Names, DNSetc.
To use the InetAddress classfor obtaining Internet addresses
To get clear understanding of sockets, datagram and stream sockets.
To implement Java networking programs using datagram sockets
4 Concept Map
Network programming involves two types of programs:
Server programs and Client programs
4.1 Client Server Program
A server program is a program that supplies services to one or multiple users who run client
programs to get access to those services. These client and server computers communicate
through well-established protocols, which decide the nature of the communications between
them.
Examples of Client Server Program:
The World Wide Web uses Web servers that provide services. The clients in the www are
Web browsers, such as Internet Explorer or Google Chrome. The protocol used to
communicate between Web servers and browsers is called HTTP. For example when you try
to access www.jinnah.edu.pk in the browser then you use http protocol.
4.2 IP Address
To identify the system on the network we use a combination of a number with three dots. This
combination is composed or 4 bytes. The decimal value represented by these bytes is known as
IP address. For example the IP address of the University’s internet gateway is 172.16.0.26.
4.3 Ports
Besides an IP address, you must use a port to get access/data from a computer over the Internet.
For example, the port number for the HTTP is 80. When you access www.jinnah.edu.pk the
request is automatically sent to port 80. If the service is running then it generates a reply which
we see in our browser.
4.4 Host Names
All the websites are mapped on an IP address. Since we cannot remember all the IP addresses so
it’s simple to map the IP addresses to the names. So the name on which the IP address of the
system is mapped is known as a Host Name. For example the Host name of the system that holds
the lectures is Dataserver which is also mapped on some IP address. You can access that system
Department of Computer Science, Page 138
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
with both name and IP address. The Domain name server is used to resolve the IP address using
the name we provide.
4.5 Loopback address
Every computer has a special host name and IP address that’s used to identify it to itself. It is
referred as localhost and IP is 127.0.0.1
4.6 InetAddress class
InetAddress is the class which is used to hold and manipulate the IP address. It is the most
powerful class in terms of its features to manipulate IPs.
If unable to resolve host name, they throw an UnknownHostException
Example:
classInetAddressTest{
public static void main(String args[])throws UnknownHostException
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.google.com");
System.out.println(address);
InetAddresssw[] = InetAddress.getAllByName("www.jinnah.edu.pk");
for(inti=0; i<sw.length; i++)
System.out.println(sw[i]);
}
}
This class is part of the java.net package, so any program that uses it must import either
java.net.InetAddress or java.net.*.
5 Homework before Lab
You must solve the following problems at home before the lab.
5.1 Problem Solution Modeling
After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.
Department of Computer Science, Page 139
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
5.1.1 Problem description:
List down advantages and disadvantages of using UDP
Can we map the UDP on some daily life example? Give one Example
5.2 Practices from home
Solve the following subtasks.
5.2.1 Task-1
Create a digital clock on server that starts from the time set by the client. If client again changes
the time, clock starts from the new time.
.
6 Procedure& Tools
In this section you will study create a synchronized thread.
6.1 Tools
Java Development Kit (JDK) 1.7
6.2 Setting-up JDK 1.7 [Expected time = 5mins]
Refer to Lab 1 sec 6.2.
6.2.1 Compile a Program
Refer to Lab 1 sec 6.2 for details.
6.2.2 Run a Program
Refer to Lab 1 sec 6.2 for details.
6.3 Walkthrough Task [Expected time = 30mins]
This task is designed to guide you towards implementing a network based communication
solution using UDP protocol. There are two steps involved to achieve the communication. One is
writing a server and the other is writing a client to generate a connect request.
6.3.1 Implementation of UDP Server
Following steps must be performed in-order to construct a UDP Server.
Department of Computer Science, Page 140
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
1. Create a DatagramSocket object
DatagramSocket dgramSocket1 = new DatagramSocket(1234);
2. Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagram
DatagramPacketinPackett = new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram
dgramSocket1.receive(inPackett);
5. Accept the sender’s address and port from the packet
InetAddressclientAddress = inPackett.getAddress();
intclientPort = inPacket.getPort();
6. Retrieve the data from the buffer
string message = new String(inPackett.getData(), 0, inPackett.getLength());
7. Create the response datagram
DatagramPacketoutPackett = new DatagramPacket(
response.getBytes(), response.length(),
clientAddress, clientPort);
8. Send the response datagram
dgramSocket1.send(outPackett)
9. Close the DatagramSocket:
dgram.close();
Final Code:
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String [] args)throws Exception
{
String s;
byte [] data=new byte[64] ;
intportnumber=3000;
DatagramSocketsoc=new DatagramSocket(portnumber);
soc.setSoTimeout(10000);
DatagramPacketpac=new DatagramPacket(data,data.length);
Department of Computer Science, Page 141
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
booleanendOfCom=false;
do
{
try
{
soc.receive(pac);
data=pac.getData();
s=new String(data);
System.out.println(s);
} catch (InterruptedIOException e){
endOfCom = true;
} catch (IOExceptionio){/* err */ }
} while (! endOfCom);
}
}
6.3.2 Implementation of UDP Client
1. Create a DatagramSocket object
DatagramSocketdgramSockett = new DatagramSocket();
2. Create the outgoing datagram
DatagramPacketoutPacket = new DatagramPacket(
message.getBytes(),
message.length(),
host, port);
3. Send the datagram message
dgramSockett.send(outPacket)
4. Create a buffer for incoming datagrams
byte[] buffer = new byte[256];
5. Create a DatagramPacket object for the incoming datagram
DatagramPacketinPackett = new DatagramPacket(buffer, buffer.length);
6. Accept an incoming datagram
dgramSockett.receive(inPackett)
7. Retrieve the data from the buffer
string response = new String(inPackett.getData(), 0, inPackett.getLength());
8. Close the DatagramSocket
dgram.close();
Department of Computer Science, Page 142
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
Final Code:
import java.net.*;
importjava.net.InetAddress.*;
public class Client
{
public static void main(String [] args)throws Exception
{
String s="abcdefghijkl";
byte [] data=s.getBytes();
intportnumber=3000;
InetAddress add=InetAddress.getByName("127.0.0.1");
DatagramSocketsoc=new DatagramSocket();
DatagramPacketpac=new DatagramPacket(data,data.length,add,portnumber);
soc.send(pac);
}
}
7 Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab11
7.1 Practice Task 1 [Expected time = 20mins]
Write a program in which you have to send the data on network and receive that data and display
that data. Data can be composed of multiple messages.
7.2 Practice Task 2 [Expected time = 20mins]
Create five files in which you stored some data. The program takes the input as a file name from
user; your task is to read the data from a file and throw that data on network and save it in
another file on the system where you receive it.
7.3 Practice Task 3 [Expected time = 20mins]
Take the five numbers from user and send them through a network to the server. Your task is to
find count of the negative and positive numbers and send the final result back to the client. The
client displays the received data on the screen.
Department of Computer Science, Page 143
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
7.4 Practice Task 4 [Expected time = 20mins]
Take two numbers from user and send them through a network to the server. Your task is to
multiply,divide,add or subtract those numbers as specified by the client on the server and send
the final result back to the client. The client displays the received data on the screen.
7.5 Out comes
After completing this lab, student will be able to understand the usage of UDP protocol and will
also be able to send and receive data between two systems using UDP protocol.
7.6 Testing
This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.
Test Cases for Practice Task-1
Sample Input at client side Sample Output at server side
This is Lab 11 This is Lab 11
We are in Lab We are in Lab
Testing 123 Testing 123
Test Cases for Practice Task-2
Sample Input at client side Sample Output at server side
File1.txt File received and stored in c:\lab11\
File4.txt File received and stored in c:\lab11\
Test Cases for Practice Task-3
Sample Input at client side Sample Output at server side
1, 20,- 5, 9, -9 Positive numbers : 3
Positive numbers : 3 Negative numbers: 2
Negative numbers: 2
Test Cases for Practice Task-3
Sample Input at client side Sample Output at server side
1 5
4
+
Department of Computer Science, Page 144
C.U.S.T.
Lab 13: Socket Programming using UDP Protocol
8 Evaluation Task (Unseen) [Expected time = 55mins for two tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
9 Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 3: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10
10 Further Reading
This section provides the references to further polish your skills.
10.1 Books
Text Book:
Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
Java Beginners Guide: http://www.oracle.com/events/global/en/java-outreach/resources/java-a-
beginners-guide-1720064.pdf
http://exampledepot.8waytrips.com/ for the package by package examples
www.youtube.com/watch?v=NvfJ0I3nfW4 for step by step video tutorial
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\
Department of Computer Science, Page 145
C.U.S.T.