Tuesday, July 29, 2008

Simplest UDP Program in Java for Beginners

The simplest program to show the data transfer among the client and server using Universal Datagram Protocol can be written as...


myServer.java

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

class myServer
{

public static void main(String []arg)throws IOException
{
int serverPort=5239;
int clientPort=5240;
int bufferSize=1024;
String data="Hello Client";
byte buffer[]= new buffer[buffersize];
DatagramSocket ds;
DatagramPacket dp;

buffer=data.getBytes();
ds=new DatagramSocket(serverPort);
dp=new DatagramPacket(buffer,buffer.length,InetAddress.getLocalHost(),clientPort);
ds.send(dp);
ds.close();
}





myClient.java

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

class myClient
{

public static void main(String []arg)throws IOException
{
int serverPort=5239;
int clientPort=5240;
int bufferSize=1024;
byte buffer[]= new buffer[buffersize];
DatagramSocket ds;
DatagramPacket dp;

ds=new DatagramSocket(clientPort);
dp=new DatagramPacket(buffer,buffer.length);
ds.recieve(dp);
System.out.println(new String(dp.getData()));
ds.close();
}


}

Explanation

We can see that there are two classes used.
DatagramSocket
DatagramPacket


DatagramSocket is used to open a socket and send or recieve packets, the reciever's port number is passed as the parameter.


DatagramPacket class has two constructors.

one for sending packets constructed as
new DatagramPacket(byte []buffer,bufferSize,Address,recieverPort)

second one is for recieving packets which is constructed as
new DatagramPacket(byte []buffer,bufferLength)



Note:- It is very important to close what you open, so always have an habit of closing every thing you open

13 Comments:

Sehan said...

Done...I'm here Today

Lady J said...

hello...i was here also

Sehan said...

Hi My Friend...Done My Work////
.................................

~MeOwChiE~ said...

who likes chocolate? i do

MeOwChiE18 said...

meow~

Lady J said...

did my work for the day...

Home said...

job done..

Home said...

visited...

Golf-1010 said...

visited.

Golf-1010 said...

hi, job done.

Home said...

hi, how are you, done job....

ChERi$ said...

Hi! Just dropped by to look at your nice blog and did several clicks too. Hope you'll also visit mine. Thanks =)

Home said...

was here...