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:

[[email protected]]# 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:

[[email protected]]# java DataConsumerMessage from Producer*/

		
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts