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
Tuesday, July 29, 2008
Simplest UDP Program in Java for Beginners
Posted by craxfun at 1:22 PM
Subscribe to:
Post Comments (Atom)
13 Comments:
Done...I'm here Today
hello...i was here also
Hi My Friend...Done My Work////
.................................
who likes chocolate? i do
meow~
did my work for the day...
job done..
visited...
visited.
hi, job done.
hi, how are you, done job....
Hi! Just dropped by to look at your nice blog and did several clicks too. Hope you'll also visit mine. Thanks =)
was here...
Post a Comment