You are on page 1of 5

UDP Programs

Aim: A Client sends DatagramPacket by DatagramSocket to a Server

File:DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}

File:DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

Aim: Write a UDP Client-Server program in which the Client sends a string and the Server
responds with the Reverse of a string.

File:DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}

File:DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);


ds.receive(dp);
String str = new String(buf);
StringBuilder sb=new StringBuilder();
sb.append(str);
sb=sb.reverse();
System.out.println(sb);
ds.close();
}
}

Aim: Write a client-server program using UDP socket. Client send the list of N strings
and server responds to the concatenation of those strings.

File:DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {

String str="",concat="";
DatagramSocket ds = new DatagramSocket(3005);
byte[] buf;
DatagramPacket dp;

while(true)
{

buf= new byte[1024];


dp= new DatagramPacket(buf, 1024);
ds.receive(dp);
str=new String(dp.getData(),0,dp.getLength());
if(!str.equals("exit"))
{
concat+=str;}
else {break;}
}
System.out.println(concat);
ds.close();

}
}

File:DSender.java
import java.net.*;
import java.util.Scanner;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp;
String str;
Scanner sc=new Scanner(System.in);

while(true)
{
System.out.println("Enter Msg:");
str=sc.nextLine();
dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3005);
ds.send(dp);
}

}
}

You might also like