Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Sending multicast datagrams</strong></p> <p>In order to send any kind of datagram in Java, be it unicast, broadcast or multicast, one needs a <code>java.net.DatagramSocket</code>:</p> <pre><code>DatagramSocket socket = new DatagramSocket(); </code></pre> <p>One can optionally supply a local port to the DatagramSocket constructor to which the socket must bind. This is only necessary if one needs other parties to be able to reach us at a specific port. A third constructor takes the local port AND the local IP address to which to bind. This is used (rarely) with multi-homed hosts where it is important on which network adapter the traffic is received.</p> <pre><code> DatagramSocket socket = new DatagramSocket(); byte[] b = new byte[DGRAM_LENGTH]; DatagramPacket dgram; dgram = new DatagramPacket(b, b.length, InetAddress.getByName(MCAST_ADDR), DEST_PORT); System.err.println("Sending " + b.length + " bytes to " + dgram.getAddress() + ':' + dgram.getPort()); while(true) { System.err.print("."); socket.send(dgram); Thread.sleep(1000); } </code></pre> <p><strong>Receiving multicast datagrams</strong></p> <p>One can use a normal DatagramSocket to send and receive unicast and broadcast datagrams and to send multicast datagrams. In order to receive multicast datagrams, however, one needs a MulticastSocket. The reason for this is simple, additional work needs to be done to control and receive multicast traffic by all the protocol layers below UDP.</p> <pre><code>byte[] b = new byte[BUFFER_LENGTH]; DatagramPacket dgram = new DatagramPacket(b, b.length); MulticastSocket socket = new MulticastSocket(DEST_PORT); // must bind receive side socket.joinGroup(InetAddress.getByName(MCAST_ADDR)); while(true) { socket.receive(dgram); // blocks until a datagram is received System.err.println("Received " + dgram.getLength() + " bytes from " + dgram.getAddress()); dgram.setLength(b.length); // must reset length field! } </code></pre> <p>For more Information:</p> <ul> <li><a href="https://docs.oracle.com/javase/7/docs/api/java/net/MulticastSocket.html" rel="nofollow noreferrer">MulticastSocket</a></li> <li><a href="https://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html" rel="nofollow noreferrer">DatagramSocket</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload