Client Server Communication - Datagram Sockets



// Socket Programing – Datagram Sockets
// Client Server Communication

// Server Program

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

public class UDPServer
{
     public static void main(String as[]) throws IOException
     {
          DatagramSocket ds;
          DatagramPacket dp;
         
          final int buf_size = 512;
          final int port = 1500;
         
          byte msg_rec[] = new byte[buf_size];
         
          try
          {
              ds = new DatagramSocket(port);
             
              dp = new DatagramPacket(msg_rec, Buf_size);
              ds.receive(dp);
                  
              String Msg = "Welcome " + (new String(dp.getData())).trim();
              System.out.println(Msg);
          }
          catch(Exception e)
          {
              System.out.println("Exception " + e);
          }
     }
}
             
             
             
             



// Socket Programing – Datagram Sockets
// Client Server Communication

// Client Program

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

public class UDPClient
{
     public static void main(String as[]) throws IOException
     {
          DatagramSocket ds;
          DatagramPacket dp;
         
          final int port = 1500;
          final int buf_size = 512;
         
          Scanner s = new Scanner(System.in);
         
          byte[] msg_send = new byte[buf_size];    
         
          try
          {
              ds = new DatagramSocket();
              System.out.print("Enter data to send : ");
              String data = s.nextLine();
             
              msg_send = data.getBytes();
              InetAddress DA = InetAddress.getByName("localhost");
             
              dp = new DatagramPacket(msg_send, msg_send.length, DA, port);
              ds.send(dp);
          }
          catch(Exception e)
          {
              System.out.println("Exception " + e);
          }
     }
}
             
             
             
             
             
             
             
             
                           
             
             
             
             

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu