Multicasting in Java
Multicasting in Java
socket.send(dgram);
Thread.sleep(1000);
}
Valid values for the constants are:
}
Values for DEST_PORT and MCAST_ADDR must match those in the sending
code for the listener to receive the datagrams sent there. BUFFER_LENGTH
should be at least as long as the data we intend to receive. If BUFFER_LENGTH
is shorter, the data will be truncated silently and dgram.getLength() will return
b.length.
The MulticastSocket.joinGroup() method causes the lower protocol layers to be
informed that we are interested in multicast traffic to a particular group address.
One may execute joinGroup() many times to subscribe to different groups. If
multiple MulticastSockets bind to the same port and join the same multicast
group, they will all receive copies of multicast traffic sent to that group/port.
As with the sending side, one can re-use ones DatagramPacket and byte-array
instances. The receive() method sets length to the amount of data received, so
remember to reset the length field in the DatagramPacket before subsequent
receives, otherwise you will be silently truncating all your incoming data to the
length of the shortest datagram previously received.
One can set a timeout on the receive() operation using
socket.setSoTimeout(timeoutInMilliseconds). If the timeout is reached before a
datagram is received, the receive() throws a java.io.InterruptedIOException. The
socket is still valid and usable for sending and receiving if this happens.