package UdpMulticastHttpExamples; import java.io.*; import java.net.*; /** * * @author mcgredo */ public class MulticastReceiver { public static final String MULTICAST_ADDRESS = "239.1.2.15"; public static final int DESTINATION_PORT = 1718; /** How many routers can be crossed */ public static final int TTL = 10; public static void main(String[] args) { try { System.out.println("MulticastReceiver started..."); // This is a java/IPv6 problem. You should also add it to the // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true // set in the "run" section of preferences. Also, typically // netbeans must be restarted after these settings. // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache System.setProperty("java.net.preferIPv4Stack", "true"); MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); multicastSocket.setTimeToLive(TTL); InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); // Join group useful on receiving side multicastSocket.joinGroup(multicastAddress); // You can join multiple groups here System.out.println("Multicast address/port: " + multicastAddress.getHostAddress() + "/" + DESTINATION_PORT); System.out.println("Multicast packets received log:"); int count = 0; // initialize while(true) { byte[] packetArray = new byte[1500]; // note use of typical MTU value DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); multicastSocket.receive(packet); count++; ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); DataInputStream dis = new DataInputStream(bais); String firstCharacters = new String(); char nextChar = ' '; while (nextChar != ';') // read and build string until terminator ; found { nextChar = dis.readChar(); firstCharacters += nextChar; } if (firstCharacters.equals("quit;")) { System.out.println("Received \"quit;\" sentinel"); break; // exit out of reading loop } int index = dis.readInt(); float firstFloat = dis.readFloat(); float secondFloat = dis.readFloat(); if (count < 10) System.out.print(" "); // prettier output formatting System.out.print(count + ". \"" + firstCharacters + "\" "); // wrap string in quote marks System.out.println("index=" + index + ", firstFloat=" + firstFloat + " secondFloat=" + secondFloat); } System.out.println("MulticastReceiver loop complete."); } catch(IOException e) { System.out.println("Problem with MulticastReceiver, see exception trace:"); System.out.println(e); } finally // clean up after exit condition { // socket/database/completion cleanup code can go here, if needed. System.out.println("MulticastReceiver finally block, complete."); } } }