Java MulticastSocket receive message

Description

Java MulticastSocket receive message

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Random;

public class Main {
   public static void main(String[] args) {
      long score = 0, run;
      Random r = new Random();
      try {//from   w w  w  .  j  a  v a 2 s.c  o  m
         int port = 8379;
         InetAddress group = InetAddress.getByName(args[0]);
         // Create a DatagramSocket
         DatagramSocket socket = new DatagramSocket();
         while (true) {
            // Fill the buffer with score generated artificially
            do {
               Thread.sleep(1000 + r.nextInt(1000));
            } while ((run = r.nextInt(7)) == 0);
            score += run;
            String msg = "score: " + score;
            byte[] out = msg.getBytes();
            // Create a DatagramPacket
            DatagramPacket pkt = new DatagramPacket(out, out.length, group, port);
            // Send the pkt
            socket.send(pkt);
            System.out.println("Sent-->" + msg);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Main {
   public static void main(String[] args) {
      byte[] inBuffer = new byte[256];
      try {/*w  w w .  j  a va2  s . c o m*/
         InetAddress address = InetAddress.getByName("224.0.0.1");
         // Create a MulticastSocket
         MulticastSocket socket = new MulticastSocket(8379);
         // Join to the multicast group
         socket.joinGroup(address);
         while (true) {
            DatagramPacket packet = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(packet);
            String msg = new String(inBuffer, 0, packet.getLength());
            System.out.println("Received<--" + msg);
         }
      } catch (IOException ioe) {
         System.out.println(ioe);
      }
   }
}



PreviousNext

Related