You are here: Home / Topics / Write a Client \Server program using DatagramPacket and DatagramSocket class in Java

Write a Client \Server program using DatagramPacket and DatagramSocket class in Java

Filed under: Java on 2023-10-25 06:50:25

// Write a Client \u2013 Server program using 
// DatagramPacket and DatagramSocket class.


// File-1 : UDPServer.java
import java.net.*;

class UDPServer 
{
public static int sPort = 2000;
public static int cPort = 3000;
public static int size = 1024;
public static  DatagramSocket ds;
public static byte buf[ ] = new byte[size];

public static void Server() throws Exception 
{
 int pos =0;

 while (true) 
 {
  int c = System.in.read();
  switch (c) 
  {
   case -1:
       System.out.println("Server Quits");
       return;
   case '\n':
       ds.send(new DatagramPacket (buf, pos, InetAddress.getLocalHost(), cPort) );
       pos = 0;
       break;
   default:
    buf[pos++] = (byte) c;
  }
 }
}

public static void main( String args[ ] ) throws Exception 
{
 ds = new DatagramSocket (sPort);
 Server();
}
}

// File-2 : UDPClient.java
import java.net.*;

class UDPClient 
{
   public static int sPort = 2000;
   public static int cPort = 3000;
   public static int size = 1024;
   public static  DatagramSocket ds;
   public static byte buf[ ] = new byte[size];

public static void Client() throws Exception
{
 while(true) 
 {
  DatagramPacket p = new DatagramPacket( buf, buf.length );
  ds.receive (p);
  System.out.println( new String ( p.getData(), 0, p.getLength() ) );
 }
}

public static void main( String args[ ] ) throws Exception 
{
 ds = new DatagramSocket ( cPort );
 Client();
}
}


Output:(for File:UDPServer.java)

Let's learn java networking


Output:(for File:UDPClient.java)

Let's learn java networking

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.