UDP

Implementing UDP Protocol for Broadcasting

UDP(User Datagram Protocol)uses a simple connectionless communication model with a minimum of protocol mechanisms. It has no handshaking dialogues, and thus exposes the user’s program to any unreliability of the underlying network; there is no promiseof delivery, ordering, or duplicate packet protection. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source od packet transmission and destination of the datagram. If error-correction facilities are needed at the network interface level, an application may use Transmission Control Protocol (TCP) or Stream Control Transmission Protocol (SCTP) which are designed for this purpose.

Program 1.
import java.net.*;
import java.io.*;
import java.util.*;
public class BroadcastServer
{
public static final int PORT = 1200;
public static void main(String args[])throws Exception{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
address = InetAddress.getByName(“228.5.6.7”);
socket = new MulticastSocket();
// join a Multicast group and send the group salutations
socket.joinGroup(address);
byte[] data = null;
for(;;)
{
 Thread.sleep(1000);
 System.out.println(“Sending “);
 String str = (new Date()).toString();
 data = str.getBytes();
 packet = new DatagramPacket(data,str.length(),address,PORT);
 //Sends the packet
 socket.send(packet);
 }
 // for
 }
 // main
 } // class BroadcastServer

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

 public class BroadcastClient{
 public static final int PORT = 1200;
 public static void main(String[] args)throws Exception{

 MulticastSocket socket;
 DatagramPacket packet;
 InetAddress address = InetAddress.getByName(“228.5.6.7”);       
 socket = new MulticastSocket(PORT);

 //join a Multicast group and send the group salutations

 socket.joinGroup(address);
 byte[] data = new byte[256];
 packet = new DatagramPacket(data,data.length);

 for(;;)
 {                               
   // receive the packets
   socket.receive(packet);
   String str = new String(packet.getData(),0,packet.getLength());
   System.out.println(” Time signal received from”+ packet.getAddress() + ” Time is : ” +str);
 }  // for

 }  // main    

}  // class Broadcast


Program 2.
//1) 1 notepad
import java.io.*;

import java.net.*;

import java.util.*;


public class QuoteServerThread extends Thread {


protected DatagramSocket socket = null;

protected BufferedReader in = null;

 protected boolean moreQuotes = true;


public QuoteServerThread() throws IOException {

this(“QuoteServerThread”);

}


public QuoteServerThread(String name) throws IOException {

super(name);

socket = new DatagramSocket(4445);


try {

in = new BufferedReader(new FileReader(“us.java”));

} catch (FileNotFoundException e) {

            System.err.println(“Could not open quote file. Serving time instead.”);

 }
    }


 public void run() {


while (moreQuotes) {

try {
                byte[] buf = new byte[256];

                    // receive request
                DatagramPacket packet = new DatagramPacket(buf, buf.length);

socket.receive(packet);

                    // figure out response

String dString = null;

if (in == null)

dString = new Date().toString();

else

dString = getNextQuote();

buf = dString.getBytes();


// send the response to the client at “address” and “port”

InetAddress address = packet.getAddress();

int port = packet.getPort();

packet = new DatagramPacket(buf, buf.length, address, port);

socket.send(packet);

} catch (IOException e) {

e.printStackTrace();

moreQuotes = false;
            }
        }

 socket.close();
    }


protected String getNextQuote() {

String returnValue = null;

try {

if ((returnValue = in.readLine()) == null) {

in.close();
        moreQuotes = false;

returnValue = “No more quotes. Goodbye.”;

}
        }
catch (IOException e) {


returnValue = “IOException occurred in server.”;

}

return returnValue;

}
}
//2) 2 notepad


import java.io.*;

import java.net.*;

import java.util.*;


public class MulticastServerThread extends QuoteServerThread {


  private long FIVE_SECONDS = 5000;


public MulticastServerThread() throws IOException
 {
        super(“MulticastServerThread”);

  }


public void run() {

   while (moreQuotes) {

    try {

 byte[] buf = new byte[256];


  // construct quote

 String dString = null;

  if (in == null)

 dString = new Date().toString();

   else

 dString = getNextQuote();

     buf = dString.getBytes();


   // send it

 InetAddress group = InetAddress.getByName(“230.0.0.1”);

 DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);

             socket.send(packet);


  // sleep for a while

try {
            sleep((long)(Math.random() * FIVE_SECONDS));

    } catch (InterruptedException e) { }

          } catch (IOException e)
{
                e.printStackTrace();

moreQuotes = false;
            }

       }

socket.close();

}
}

//3 notepad

public class MulticastServer
{
    public static void main(String[] args) throws java.io.IOException
 {

 new MulticastServerThread().start();

 }
}


// 4 notepad

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

import java.util.*;


public class MulticastClient {


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


 MulticastSocket socket = new MulticastSocket(4446);

 InetAddress address = InetAddress.getByName(“230.0.0.1”);

socket.joinGroup(address);


 DatagramPacket packet;


 // get a few quotes

for (int i = 0; i < 5; i++) {


        byte[] buf = new byte[256];

           packet = new DatagramPacket(buf, buf.length);

          socket.receive(packet);


 String received = new String(packet.getData(), 0, packet.getLength());

           System.out.println(“Quote of the Moment: ” + received);

    }


socket.leaveGroup(address);

socket.close();

 }

}
/* on one comand promp> javac QuoteServerThread.java
>javac MulticastServer
>javc MulticastServer
==>make sure to change input file name in code of QuoteServerThread code
on second command promp>javac MulticastClient.java
>java MulticastClient

*/UDP provides an unreliable packet delivery system built on top of the IP
protocol. As with IP, each packet is an individual, and is handled separately.
Because of this, the amount of data that can be sent in a UDP packet is limited to
the amount that can be contained in a single IP packet. Thus, a UDP packet
contain at most 65507 bytes (this is the 65535-byte IP packet size minus theminimum IP header of 20 bytes and minus the 8-byte UDP header).UDP packets can arrive out of order or not at all. No packet has any knowledge of
the preceding or following packet. The recipient does not acknowledge packets, sothe sender does not know that the transmission was successful. UDP has noprovisions for flow control–packets can be received faster than they can be used.We call this type of communication connectionless because the packets have norelationship to each other and because there is no state maintained.


The destination IP address and port number is encapsulated in each UDP packet.
These two numbers together uniquely identify the recipient and are used by the
underlying operating system to deliver the packet to a specific process
(application).

One way to think of UDP is by analogy to communications via a letter.
 You write
the letter (this is the data you are sending);
 put the letter inside an envelope (the
UDP packet); address the envelope (using an IP address and a port number);
 put
your return address on the envelope (your local IP address and port number)
 and then you send the letter.
Like a real letter, you have no way of knowing whether a UDP packet was
received. If you send a second letter one day after the first, the second one may be received
before the first. Or, the second one may never be received.
So why use UDP if it unreliable? Two reasons: speed and overhead.


UDP packets

have almost no overhead–you simply send them then forget about them. And
they are fast, since there is no acknowledgement required for each packet. Keep in

mind the degree of unreliability we are talking about. For all practical purposes, an

Ethernet breaks down if more than about 2 percent of all packets are lost. So,


when we say unreliable, the worst-case loss is very small.
UDP is appropriate for the many network services that do not require guaranteed

delivery. An example of this is a network time service. Consider a time daemon
that issues a UDP packet every second so computers on the LAN can
synchronize their clocks. If a packet is lost, it’s no big deal–the next one will be

by in another second and will contain all necessary information to accomplish the
task.

Another common use of UDP is in networked, multi-user games, where a player’s

position is sent periodically. Again, if one position update is lost, the next one

will contain all the required information.

A broad class of applications is built on top of UDP using streaming protocols.

With streaming protocols, receiving data in real-time is far more important than

guaranteeing delivery. Examples of real-time streaming protocols are RealAudio
and RealVideo which respectively deliver real-time streaming audio and video over

the Internet. The reason a streaming protocol is desired in these cases is because if


an audio or video packet is lost, it is much better for the client to see this as noise

or “drop-out” in the sound or picture rather than having a long pause while the

client software stops the playback, requests the missing data from the server.

That would result in a very choppy, bursty playback which most people fin

unacceptable, and which would place a heavy demand on the server.

Creating UDP ServersTo create a server with UDP, do the following:Create a attached to a port.1.DatagramSocketint port = 1234;
DatagramSocket socket = new DatagramSocket(port);Allocate space to hold the incoming packet, and create an instance of

2.to hold the incoming data.
DatagramPacket byte[] buffer = new byte[1024];DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

3.Block until a packet is received, then extract the information you need from the packet.


// Block on receive()

socket.receive(packet);


// Find out where packet came from


// so we can reply to the same host/port

InetAddress remoteHost = packet.getAddress

int remotePort = packet.getPort();


// Extract the packet data

byte[] data = packet.getData();


The server can now process the data it has received from the client, and issue an

appropriate reply in response to the client’s request.

Creating UDP Clients
Writing code for a UDP client is similar to what we did for a server. Again, we
need a and a


. The only real difference is that

DatagramSocket

DatagramPacket

we must specify the destination address with each packet, so the form of the

constructor used here specifies the destination host and port

DatagramPacket

number. Then, of course, we initially send packets instead of receiving.

First allocate space to hold the data we are sending and create an instance of

1.to hold the data.

DatagramPacket
 byte[] buffer = new byte[1024];

int port = 1234;

InetAddress host = InetAddress.getByName(“magelang.com”);

DatagramPacket packet =

new DatagramPacket(buffer, buffer.length, host, port);
Create a
and send the packet using this socket.


2.

DatagramSocket

DatagramSocket socket = new DatagramSocket();

socket.send(packet);


The constructor that takes no arguments will allocate a free local

DatagramSocket

port to use. You can find out what local port number has been allocated for your


socket, along with other information about your socket if needed.

// Find out where we are sending from

InetAddress localHostname = socket.getLocalAddress();

int localPort = socket.getLocalPort();

The client then waits for a reply from the server. Many protocols require t

server to reply to the host and port number that the client used, so the client c
now invoke to wait for information from the server.



socket.receive();



TCP guarantees the delivery o f packets and preserves their order on destination. Sometimes these features are not required and it since they do not come without performance costs, it would be use a lighter transport protocol. This kind of service is accomplished by the UDP protocol which conveys datagram packets .Datagram packets are used to implement a connectio nless packet delivery service suppo rted by the UDP protocol. Each message is transferred from source machine to destination based on


information contained within that packet. That means, each packet needs to have destination address and each packet might be routed differently, and might arrive in an y order. Packet delivery is not guaranteed.


The format of datagram packet is:

| Msg | length | Host | serverPort |


Java supports datagram communication through the following classes:
• DatagramPacket
• DatagramSocket

The class contains several constructors that can be used for creating packet
object. One of them is:
DatagramPacket (byte[] buf, int length,InetAddress address, int port);

This constructor is used for creating a datagram packet for sending packets o f length length to the specified port number on the specified ho st. The message to be transmitted is indicated in the first argument. The key methods of class DatagramPacket are:

byte[] getData()
-Returns the data buffer.
int getLength()
-Returns the length of the data to be sent or the length of the data received.
void setData(byte[] buf)
-Sets the data buffer for this packet.
void setLength(int length)
-Sets the length for this packet.


The class DatagramSocket supports various metho ds that can be used for transmitting or receiving data a datagram o ver the network. The two key methods are:
void send(DatagramPacket p)
-Sends a datagram packet from this socket.
void receive(DatagramPacket p)
Receives a datagram packet from this socket.

A simple UDP server program that waits for client’s requests and then accepts the message (datagram) and sends back the same message is given below.


// UDPServer.java: A simple UDP server program.
import java.net.*;
import java.io.*;
public class UDPServer {

public static void main(String args[]){
DatagramSocket aSocket = null;
if (args.length < 1) {
System.out.println(“Usage: java UDPServer <Port Number>”);
System.exit(1);
}


try {
int socket_no = Integer.valueOf(args[0]).intValue();
DatagramSocket asocket = new DatagramSocket(socket_no);
byte[] buffer = new byte[1000];

while(true) {
DatagramPacket request = new DatagramPacket(bufferbuffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),
request.getLength(),request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e) {
System.out.println(“Socket: ” + e.getMessage());
}


catch (IOException e) {
System.out.println(“IO: ” + e.getMessage());
}


finally {
if (aSocket != null)
aSocket.close();
}
}
}





import java.net.*;
import java.io.*;
public class UDPClient {


public static void main(String args[]){
// args give message contents and server hostname
DatagramSocket aSocket = null;
if (args.length < 3) {
System.out.println(
“Usage: java UDPClient <message> <Host name> <Port number>”);
System.exit(1);
}


try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();


DatagramPacket request =
new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println(“Reply: ” + new String(reply.getData()));
}


catch (SocketException e) {
System.out.println(“Socket: ” + e.getMessage());
}
catch (IOException e) {
System.out.println(“IO: ” + e.getMessage());
}


finally {
if (aSocket != null)
aSocket.close();
}
}
}

Program 2)Practical usage of UDP protocol
import java.net.*;
import java.io.*;

public class EchoServer
{
//Initialize Port number and Packet Size
static final int serverPort = 1026;
static final int packetSize = 1024;
public static void main(String args[])throws SocketException{
DatagramPacket packet;
DatagramSocket socket;
byte[] data; // For data to be Sent in packets


int clientPort;
InetAddress address;
String str;
socket = new DatagramSocket(serverPort);


for(;;)
{
data = new byte[packetSize];

// Create packets to receive the message
packet = new DatagramPacket(data,packetSize);
System.out.println(“Waiting to receive the packets”);
try{
// wait infinetely for arrive of the packet
socket.receive(packet);
}catch(IOException ie)
{
System.out.println(” Could not Receive :”+ie.getMessage());
System.exit(0);
}
// get data about client in order to echo data back
address = packet.getAddress();
clientPort = packet.getPort();
// print string that was received on server’s console
str = new String(data,0,0,packet.getLength());
System.out.println(“Message :”+ str.trim());
System.out.println(“From :”+address);
// echo data back to the client
// Create packets to send to the client
packet = new DatagramPacket(data,packetSize,address,clientPort);
try
{
// sends packet
socket.send(packet);
}
catch(IOException ex)
{
System.out.println(“Could not Send : “+ex.getMessage());
System.exit(0);
}
} // for loop
} // main

} // class EchoServer


// Client Program


import java.net.*;


import java.io.*;

public class EchoClient{
static final int serverPort = 1026;
static final int packetSize = 1024;

public static void main(String args[]) throws UnknownHostException, SocketException
{
DatagramSocket socket; //How we send packets
DatagramPacket packet; //what we send it in
InetAddress address; //Where to send
String messageSend; //Message to be send
String messageReturn; //What we get back from the Server
byte[] data;
//Checks for the arguments that sent to the java interpreter
// Make sure command line parameters correctr
if(args.length != 2)
{
System.out.println(“Usage Error :Java EchoClient < Server name> < Message>”);
System.exit(0);
}
// Gets the IP address of the Server
address = InetAddress.getByName(args[0]);
socket = new DatagramSocket();
data = new byte[packetSize];
messageSend = new String(args[1]);
messageSend.getBytes(0,messageSend.length(),data,0);
// remember datagrams hold bytes
packet = new DatagramPacket(data,data.length,address,serverPort);
System.out.println(” Trying to Send the packet “);
try
{
// sends the packet
socket.send(packet);
}
catch(IOException ie)
{
System.out.println(“Could not Send :”+ie.getMessage());
System.exit(0);
}
// packet is reinitialized to use it for recieving
packet = new DatagramPacket(data,data.length);
try
{

// Receives the packet from the server
socket.receive(packet);
}
catch(IOException iee)
{
System.out.println(“Could not receive : “+iee.getMessage() );
System.exit(0);
}
// display message received
messageReturn = new String (packet.getData(),0);
System.out.println(“Message Returned : “+ messageReturn.trim());
} // main
} // Class EchoClient