devxlogo

Perform Connectionless Communication Between Producer and Consumer

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 DataProducerMessage 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 DataConsumerMessage from Producer*/

		
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist