UDP Datagram sample program in Java

By: Jagan Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

For most of your internetworking needs, you will be happy with TCP/IP-style networking. It provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes many complicated algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative.

Datagrams are bundles of information passed between machines. They are somewhat like a hard throw from a well-trained but blindfolded catcher to the third baseman. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. Likewise, when the datagram is received, there is no assurance that it hasn't been damaged in transit or that whoever sent it is still there to receive a response.

Java implements datagrams on top of the UDP protocol by using two classes: The DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed.

// Demonstrate Datagrams.
import java.net.*;
class WriteServer {
public static int serverPort = 666;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");
case '\\r':
case '\\n':
ds.send(new DatagramPacket(buffer,pos,
buffer[pos++] = (byte) c;
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer,
System.out.println(new String(p.getData(), 0,
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
} else {
ds = new DatagramSocket(clientPort);

This sample program is restricted by the DatagramSocket constructor to running between two ports on the local machine. To use the program, run

java WriteServer

in one window; this will be the client. Then run

java WriteServer 1

This will be the server. Anything that is typed in the server window will be sent to the client window after a newline is received.
Note This example requires that your computer be connected to the Internet.

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

I am so confused and a total beginner and no good with programming at the moment, because I am so tensed with all the tests and projects going on at school. Now I wanted to ask you since I haven't even a chance to manage this homework.

Which I must say is much more to me. Could someone of you help me to write a code in 2 days to write an UDP-Protocol to send and receive files by sending a file through splitted parts.

And put in some kind of asurance that it has received the client? If not continue to send part from the interuption point till the end? And this all with a timer ....where I can see how much time it takes in total, to send and receive the file?


I have nothing to loose, only my pride...

View Tutorial          By: Jena at 2011-06-11 17:39:39
2. View Comment

having errors in the programme

View Tutorial          By: dfdff at 2011-12-21 11:42:10

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Jagan
Importing a Certificate for the CA example using keytool in Java
The if-then-else Statement in Java
WHERE Clauses in SQL
The TryCatchFinally Interface in JSP
assert() Function Example program in C
Guidelines for Struts Application Development
Using printf function in C
File Inclusion in C
Using Multiple Message Resource Bundles in Struts
While and For Loops in C
Arrays sample program in C
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Using cout.fill() in C++
Types of Profiles in J2ME
DateField sample program in J2ME

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
PushbackReader sample program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java