Tuesday, May 29, 2012

Datagram Server in Java

// Datagram Server or UDP server
// purpose of this example is to provide a fare idea about the working of UDP client server
// this server example works with client example and link to the client example is given at the end of this code
// example works on the concept of UDP protocol (simple transmission model without implicit handshaking)


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

public class Server {

  
    public static void main(String[] args) {
       
        DatagramSocket serverSkt= null;
        try{
            serverSkt = new DatagramSocket(3030);
        }
        catch(SocketException exp)
        {
            System.out.println(exp);
        }
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];
        while(true)
          {
            DatagramPacket receivePkt = new DatagramPacket(receiveData, receiveData.length);
            try{
                serverSkt.receive(receivePkt);
            }
            catch(IOException exp)
            {
                System.out.println(exp);
            }
            String sentence = new String( receivePkt.getData());
            System.out.println("RECEIVED: " + sentence);
            InetAddress IPAddress = receivePkt.getAddress();
            int port = receivePkt.getPort();
            String capitalizedSentence = sentence.toUpperCase();
            sendData = capitalizedSentence.getBytes();
            DatagramPacket sendPkt =
            new DatagramPacket(sendData, sendData.length, IPAddress, port);
            try{
            serverSkt.send(sendPkt);
            }
            catch(IOException exp)
            {
                System.out.println(exp);
            }  
        }
      }
       
    }

Datagram Client Source

No comments:

Post a Comment