Skip to Content
Java Network Programming, Second Edition
book

Java Network Programming, Second Edition

by Elliotte Rusty Harold
August 2000
Intermediate to advanced
760 pages
21h
English
O'Reilly Media, Inc.
Content preview from Java Network Programming, Second Edition

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

Elliotte Rusty Harold
Java Concurrency, 2/e

Java Concurrency, 2/e

Douglas Schmidt

Publisher Resources

ISBN: 1565928709Supplemental ContentCatalog PageErrata