Working with Multicast Sockets

Enough theory. In Java, you multicast data using the java.net.MulticastSocket class. This is a subclass of java.net.DatagramSocket:

public class MulticastSocket extends DatagramSocket

As you would expect, MulticastSocket’s behavior is very similar to DatagramSocket’s: you put your data in DatagramPacket objects that you send and receive with the MulticastSocket. Therefore, I won’t repeat the basics; this discussion assumes that you already know how to work with datagrams. However, if you’re jumping around in this book rather than reading it cover to cover, now might be a good time to go back and read the previous chapter on UDP.

To receive data that is being multicast from a remote site, you first create a MulticastSocket with the MulticastSocket( ) constructor. Next, you join a multicast group using the MulticastSocket’s joinGroup( ) method. This signals the routers in the path between you and the server to start sending data your way and tells the local host that it should pass you IP packets addressed to the multicast group.

Once you’ve joined the multicast group, you receive UDP data just as you would with a DatagramSocket. That is, you create a DatagramPacket with a byte array that serves as a buffer for data, and enter a loop in which you receive the data by calling the receive( ) method inherited from the DatagramSocket class. When you no longer want to receive data, you leave the multicast group by invoking the socket’s leaveGroup( ) method. ...

Get Java Network Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.