How to Create an Multicast Client/Server with Oracle JDK

Client

import static java.lang.System.out;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public final class JdkClient {

  public static void main(final String[] args) throws Exception {
    final MulticastSocket client = new MulticastSocket(45588);

    client.joinGroup(InetAddress.getByName("224.0.1.0")); // 224.0.0.XXX is reserved

    final DatagramPacket packet = new DatagramPacket(new byte[13], 13);

    client.receive(packet);

    out.write(packet.getData());

    client.close();
  }

}

Server

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public final class JdkServer {

  public static void main(final String[] args) throws Exception {
    final MulticastSocket server = new MulticastSocket();

    final DatagramPacket packet = new DatagramPacket("Simples Assim".getBytes(), 13, InetAddress.getByName("224.0.1.0"), 45588);

    while (true)
      server.send(packet);

  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s