dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Perform Connectionless Communication Between Producer and Consumer

See how to perform connectionless communication between the producer and the consumer.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


See how to perform connectionless communication between the producer and the consumer.

DatagramSocket - Data producer

This class produces data and sends it to the specified IP address and port. It really does not bother if a real consumer is available.

DatagramSocket - Data consumer

This class consumes data from the port.

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

public class DataProducer{  
     public static void main(String args[])
   {
      DataProducer dataProducer = new DataProducer();
      dataProducer.proceed();
   }
   
   private void proceed()
   {
      try{
         int port = 4567;
         String ipAddress = "127.0.0.1" ;
         DatagramSocket datagramSocket = new DatagramSocket();  
         String messageString = "Message from Producer";  
         InetAddress inetIpAddress = InetAddress.getByName(ipAddress);  
          
         DatagramPacket datagramPacket = new DatagramPacket(messageString.getBytes(), messageString.length(), inetIpAddress, port);  
         datagramSocket.send(datagramPacket);  
         System.out.println("Message sent");  
         datagramSocket.close();  
      }catch(IOException ioe)
      {
         System.out.println("Exception: " + ioe.getMessage() );
      }
   }  
}  

/*

Expected output:

[root@mypc]# java DataProducer
Message sent

*/

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

public class DataConsumer{  
     public static void main(String args[])
   {
      DataConsumer dataConsumer = new DataConsumer();
      dataConsumer.proceed();
   }
   
   private void proceed()
   {
      try{
         int port = 4567;
         DatagramSocket datagramSocket = new DatagramSocket(port);  
         byte[] buf = new byte[1024];  
         DatagramPacket datagramPacket = new DatagramPacket(buf, 1024);  
         datagramSocket.receive(datagramPacket);  
         String receivedMessageString = new String(datagramPacket.getData(), 0, datagramPacket.getLength());  
         System.out.println(receivedMessageString);  
         datagramSocket.close();  
      }catch(IOException ioe)
      {
         System.out.println("Exception: " + ioe.getMessage() );
      }
   }  
}  

/*

Expected output:

[root@mypc]# java DataConsumer
Message from Producer

*/

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date