Home » Tip Bank » Java
  • Comment on this Article
Language: Java
Expertise: Intermediate
Sep 13, 2019
  • facebook
  • twitter
  • in
  • Email

WEBINAR:

On-Demand

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


Watch

Perform Connectionless Communication Between Producer and Consumer

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

*/
 
M S Sridhar
 
Submit a Tip
Browse "Java" Tips
Browse All Tips
eloquentjavascript.net
htmlgoodies.com