Create Multicast Sender using DatagramSocket - Java Network

Java examples for Network:UDP

Description

Create Multicast Sender using DatagramSocket

Demo Code

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

public class MulticastSender {
  public static void main(String[] args) {
    byte[] outBuf;
    final int PORT = 8888;

    try {/* w w w  . j  av a  2 s  . c  o m*/
      DatagramSocket socket = new DatagramSocket();
      long counter = 0;
      String msg;

      while (true) {
        msg = "This is multicast! " + counter;
        counter++;
        outBuf = msg.getBytes();

        //Send to multicast IP address and port
        InetAddress address = InetAddress.getByName("224.2.2.3");
        DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);

        socket.send(outPacket);

        System.out.println("Server sends : " + msg);
        try {
          Thread.sleep(500);
        } catch (InterruptedException ie) {
        }
      }
    } catch (IOException ioe) {
      System.out.println(ioe);
    }
  }
}

Related Tutorials