Example usage for java.net MulticastSocket close

List of usage examples for java.net MulticastSocket close

Introduction

In this page you can find the example usage for java.net MulticastSocket close.

Prototype

public void close() 

Source Link

Document

Closes this datagram socket.

Usage

From source file:net.pms.network.UPNPHelper.java

/**
 * Send alive./* www .j a  v a  2s .c  om*/
 */
public static void sendAlive() {
    logger.debug("Sending ALIVE...");
    MulticastSocket multicastSocket = null;

    try {
        multicastSocket = getNewMulticastSocket();
        InetAddress upnpAddress = getUPNPAddress();
        multicastSocket.joinGroup(upnpAddress);

        sendMessage(multicastSocket, "upnp:rootdevice", ALIVE);
        sendMessage(multicastSocket, PMS.get().usn(), ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:device:MediaServer:1", ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ContentDirectory:1", ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ConnectionManager:1", ALIVE);
    } catch (IOException e) {
        logger.debug("Error sending ALIVE message", e);
    } finally {
        if (multicastSocket != null) {
            // Clean up the multicast socket nicely
            try {
                InetAddress upnpAddress = getUPNPAddress();
                multicastSocket.leaveGroup(upnpAddress);
            } catch (IOException e) {
            }

            multicastSocket.disconnect();
            multicastSocket.close();
        }
    }
}

From source file:com.all.landownloader.discovery.LanDiscoverySocket.java

public LanDiscoveredPeer listen() throws IOException, IllegalArgumentException {
    MulticastSocket socket = new MulticastSocket(PORT);
    socket.joinGroup(addressGroup);//  w  w  w.jav a2  s. c  o m
    byte[] buf = new byte[BUF_LENGTH];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);
    socket.leaveGroup(addressGroup);
    socket.close();

    InetAddress address = packet.getAddress();
    byte[] remotePortBuffer = new byte[4];
    System.arraycopy(buf, HEADER_LENGTH, remotePortBuffer, 0, remotePortBuffer.length);
    LanDiscoveredPeer discoveredPeer = new LanDiscoveredPeer(address, LanUtils.decodeInt(remotePortBuffer));

    if (eq(BYE_MSG, buf, HEADER_LENGTH)) {
        addresses.remove(address);
        RegisteredAddress remove = quickLeases.remove(address);
        if (remove != null) {
            leases.remove(remove);
        }
        return null;
    }

    RegisteredAddress reg = quickLeases.get(discoveredPeer);
    long nextLeaseTime = System.currentTimeMillis() + this.leaseTime;
    if (reg == null) {
        reg = new RegisteredAddress(nextLeaseTime, discoveredPeer);
        quickLeases.put(discoveredPeer, reg);
    } else {
        reg.setLease(nextLeaseTime);
    }
    if (eq(ANNOUNCE_MSG, buf, HEADER_LENGTH)) {
        reply(address);
    }
    leases.add(reg);
    addresses.add(discoveredPeer);
    return discoveredPeer;
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

private void sendByeBye(UPNPMBeanDevice dv) throws IOException {
    InetAddress group = InetAddress.getByName("239.255.255.250");
    java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort());
    multi.setInterface(bindAddress.getAddress());
    multi.setTimeToLive(dv.getSSDPTTL());

    List packets = getByeByeReplyMessages(dv);
    for (int i = 0; i < packets.size(); i++) {
        String packet = (String) packets.get(i);
        if (log.isDebugEnabled())
            log.debug("Sending ssdp:byebye message on 239.255.255.250:1900 multicast address:\n"
                    + packet.toString());
        byte[] pk = packet.getBytes();
        multi.send(new DatagramPacket(pk, pk.length, group, 1900));
    }/*from  w w  w.j  av  a 2  s  .c  om*/
    multi.close();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

private void sendHello(UPNPMBeanDevice dv) throws IOException {
    InetAddress group = InetAddress.getByName("239.255.255.250");
    java.net.MulticastSocket multi = new java.net.MulticastSocket(bindAddress.getPort());
    multi.setInterface(bindAddress.getAddress());
    multi.setTimeToLive(dv.getSSDPTTL());

    List packets = getReplyMessages(dv, true, dv.getSSDPAliveDelay());
    for (int i = 0; i < packets.size(); i++) {
        String packet = (String) packets.get(i);
        if (log.isDebugEnabled())
            log.debug("Sending ssdp alive message on 239.255.255.250:1900 multicast address:\n"
                    + packet.toString());
        byte[] pk = packet.getBytes();
        multi.send(new DatagramPacket(pk, pk.length, group, 1900));
    }/* w w w .j  a  v  a  2  s .  c o  m*/
    multi.close();
}

From source file:com.summit.jbeacon.beacons.MultiCastResourceBeacon.java

/**
 * refresh the resources that are available.
 * @throws MultiCastResourceBeaconException if
 * the data fails to be refreshed/*from ww w.  j a v a2 s  .  co m*/
 */
public final void refreshData() throws MultiCastResourceBeaconException {
    while (!listenerThread.isRunning()) {
        try {
            log.debug("Waiting for server to start.");
            Thread.sleep(threadSleep);
        } catch (InterruptedException ex) {
            log.warn("Thread death while waiting for listener to run.");
        }

    }
    log.info("Attempting to refresh data.");
    if (listeningSocket == null) {
        throw new MultiCastResourceBeaconException(
                "Beacon is not " + "listening for responses. Initialize the " + "listener first!");
    }
    MulticastSocket s = null;
    try {
        s = new MulticastSocket();
        s.setReuseAddress(true);
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException("Error creating multicast socket...", ex);
    }

    String broadcastMessage = getBroadcastText() + " : " + getIp() + ":" + getHostName() + ":"
            + listeningSocket.getLocalPort();
    byte[] buf = broadcastMessage.getBytes();
    DatagramPacket pack = null;
    try {
        log.info("Multicast port: " + getGroupPort());
        log.info("Multicast group: " + getGroupAddress());
        pack = new DatagramPacket(buf, buf.length, InetAddress.getByName(getGroupAddress()), getGroupPort());
    } catch (UnknownHostException ex) {
        throw new MultiCastResourceBeaconException("Error creating datagram.", ex);
    }
    try {
        s.send(pack);
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException("Error sending message.", ex);
    }
    s.close();
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

public void run() {
    InetAddress group = null;/*  w  w  w  .  j  av a 2s.  com*/
    try {
        group = InetAddress.getByName("239.255.255.250");
        skt = new java.net.MulticastSocket(1900);
        skt.setInterface(bindAddress.getAddress());
        skt.joinGroup(group);
    } catch (IOException ex) {
        log.error("Error during multicast socket creation, thread cannot start", ex);
        return;
    }
    isRunning = true;
    while (isRunning) {
        try {
            byte[] buffer = new byte[4096];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, bindAddress.getPort());
            skt.receive(packet);
            String received = new String(packet.getData(), 0, packet.getLength());
            if (log.isDebugEnabled())
                log.debug("Received message:\n" + received);
            HttpRequest req = new HttpRequest(received);
            if (req.getHttpCommand().equals("M-SEARCH")) {
                String man = req.getHTTPHeaderField("MAN");
                if (man.equals("\"ssdp:discover\"")) {
                    String searchTarget = req.getHTTPHeaderField("ST");
                    // TODO check ALL devices search target
                    //if ( searchTarget.equals( Discovery.ALL_DEVICES ) ) {
                    if (searchTarget.equals(Discovery.ROOT_DEVICES)) {
                        java.net.MulticastSocket multi = new java.net.MulticastSocket();
                        multi.setInterface(bindAddress.getAddress());
                        for (Iterator i = handledDevices.iterator(); i.hasNext();) {
                            UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next();
                            List packets = getReplyMessages(dv, false, dv.getSSDPAliveDelay());
                            for (int z = 0; z < packets.size(); z++) {
                                String pack = (String) packets.get(z);
                                if (log.isDebugEnabled())
                                    log.debug("Sending http reply message on " + packet.getAddress() + ":"
                                            + packet.getPort() + " multicast address:\n" + pack.toString());
                                byte[] pk = pack.getBytes();
                                multi.setTimeToLive(dv.getSSDPTTL());
                                multi.send(new DatagramPacket(pk, pk.length, packet.getAddress(),
                                        packet.getPort()));
                            }
                        }
                        multi.close();
                    } else {
                        // TODO check a specific search target
                    }
                }
            }
        } catch (IOException ex) {
            if (isRunning) {
                log.error("Error during multicast socket IO operations", ex);
            }
        }
    }
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Starts up two threads: one to broadcast UPnP ALIVE messages and another
 * to listen for responses. /*from   w  w w.jav  a  2 s .c o m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void listen() throws IOException {
    Runnable rAlive = new Runnable() {
        @Override
        public void run() {
            int delay = 10000;

            while (true) {
                sleep(delay);
                sendAlive();

                // The first delay for sending an ALIVE message is 10 seconds,
                // the second delay is for 20 seconds. From then on, all other
                // delays are for 180 seconds.
                switch (delay) {
                case 10000:
                    delay = 20000;
                    break;
                case 20000:
                    delay = 180000;
                    break;
                }
            }
        }
    };

    aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender");
    aliveThread.start();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean bindErrorReported = false;

            while (true) {
                MulticastSocket multicastSocket = null;

                try {
                    // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166
                    multicastSocket = new MulticastSocket(configuration.getUpnpPort());

                    if (bindErrorReported) {
                        logger.warn(
                                "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!");
                    }

                    NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

                    try {
                        // Setting the network interface will throw a SocketException on Mac OSX
                        // with Java 1.6.0_45 or higher, but if we don't do it some Windows
                        // configurations will not listen at all.
                        if (ni != null) {
                            multicastSocket.setNetworkInterface(ni);
                        } else if (PMS.get().getServer().getNetworkInterface() != null) {
                            multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface());
                            logger.trace("Setting multicast network interface: "
                                    + PMS.get().getServer().getNetworkInterface());
                        }
                    } catch (SocketException e) {
                        // Not setting the network interface will work just fine on Mac OSX.
                    }

                    multicastSocket.setTimeToLive(4);
                    multicastSocket.setReuseAddress(true);
                    InetAddress upnpAddress = getUPNPAddress();
                    multicastSocket.joinGroup(upnpAddress);

                    while (true) {
                        byte[] buf = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
                        multicastSocket.receive(receivePacket);

                        String s = new String(receivePacket.getData());

                        InetAddress address = receivePacket.getAddress();

                        if (s.startsWith("M-SEARCH")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            if (configuration.getIpFiltering().allowed(address)) {
                                logger.trace(
                                        "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]");

                                if (StringUtils.indexOf(s,
                                        "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:service:ContentDirectory:1");
                                }

                                if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) {
                                    sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
                                }

                                if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, "ssdp:all") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, PMS.get().usn()) > 0) {
                                    sendDiscover(remoteAddr, remotePort, PMS.get().usn());
                                }
                            }
                        } else if (s.startsWith("NOTIFY")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]");
                        }
                    }
                } catch (BindException e) {
                    if (!bindErrorReported) {
                        logger.error("Unable to bind to " + configuration.getUpnpPort()
                                + ", which means that PMS will not automatically appear on your renderer! "
                                + "This usually means that another program occupies the port. Please "
                                + "stop the other program and free up the port. "
                                + "PMS will keep trying to bind to it...[" + e.getMessage() + "]");
                    }

                    bindErrorReported = true;
                    sleep(5000);
                } catch (IOException e) {
                    logger.error("UPNP network exception", e);
                    sleep(1000);
                } finally {
                    if (multicastSocket != null) {
                        // Clean up the multicast socket nicely
                        try {
                            InetAddress upnpAddress = getUPNPAddress();
                            multicastSocket.leaveGroup(upnpAddress);
                        } catch (IOException e) {
                        }

                        multicastSocket.disconnect();
                        multicastSocket.close();
                    }
                }
            }
        }
    };

    listenerThread = new Thread(r, "UPNPHelper");
    listenerThread.start();
}

From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {/*from   w  w  w  .j  a  v a2  s  .  co m*/

        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);

        // Request-Packet-Constructor
        StringBuffer discoveryMessage = new StringBuffer();
        discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
        discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
        discoveryMessage.append("ST: upnp:rootdevice\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\r\n");
        discoveryMessage.append("\r\n");
        logger.trace("Request: {}", discoveryMessage.toString());
        byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
        DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
                dstAddress);

        // Send multi-cast packet
        MulticastSocket multicast = null;
        try {
            multicast = new MulticastSocket(null);
            multicast.bind(srcAddress);
            logger.trace("Source-Address = '{}'", srcAddress);
            multicast.setTimeToLive(4);
            logger.debug("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        DatagramSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    receivePacket = new DatagramPacket(new byte[1536], 1536);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    logger.trace("Received message: {}", message);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String label = "WeMo Device";
                            String wemoUDN = null;
                            String wemoLocation = null;
                            String wemoFriendlyName = null;
                            String wemoModelName = null;
                            ThingUID uid = null;

                            if (message != null) {
                                if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
                                        || message.contains("Motion-1_0")
                                        || message.contains("Lightswitch-1_0")) {
                                    wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
                                            "::upnp:rootdevice");
                                    logger.debug("Wemo device with UDN '{}' found", wemoUDN);
                                    wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
                                            "/setup.xml");
                                    if (wemoLocation != null) {
                                        try {
                                            int timeout = 5000;
                                            String response = HttpUtil.executeUrl("GET",
                                                    wemoLocation + "/setup.xml", timeout);
                                            wemoFriendlyName = StringUtils.substringBetween(response,
                                                    "<friendlyName>", "</friendlyName>");
                                            logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
                                                    wemoLocation);
                                            wemoModelName = StringUtils.substringBetween(response,
                                                    "<modelName>", "</modelName>");
                                            logger.trace("Wemo device '{}' has model name '{}'",
                                                    wemoFriendlyName, wemoModelName);
                                            label = "Wemo" + wemoModelName;

                                            switch (wemoModelName) {
                                            case "Socket":
                                                logger.debug(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);

                                                break;
                                            case "Insight":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
                                                break;
                                            case "LightSwitch":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
                                                break;
                                            case "Motion":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
                                                break;
                                            }
                                            Map<String, Object> properties = new HashMap<>(4);
                                            properties.put(UDN, wemoUDN);
                                            properties.put(LOCATION, wemoLocation);

                                            DiscoveryResult result = DiscoveryResultBuilder.create(uid)
                                                    .withProperties(properties).withLabel(label).build();
                                            thingDiscovered(result);

                                        } catch (Exception te) {
                                            logger.error("Could not discover WeMo device", te);
                                        }
                                    }
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not send Wemo device discovery", e);
    }

}

From source file:org.openhab.binding.wemo.internal.WemoBinding.java

public void wemoDiscovery() {
    logger.debug("wemoDiscovery() is called!");
    try {/*w  w  w  . j  a  va2  s.  c  o m*/
        final int SSDP_PORT = 1900;
        final int SSDP_SEARCH_PORT = 1901;

        // Broadcast address
        final String SSDP_IP = "239.255.255.250";

        // Connection timeout
        int TIMEOUT = 1000;

        // Send from localhost:1901
        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        // Send to 239.255.255.250:1900
        InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);

        // Request-Packet-Constructor
        StringBuffer discoveryMessage = new StringBuffer();
        discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
        discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\r\n");
        discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n");
        discoveryMessage.append("\r\n");
        logger.trace("Request: {}", discoveryMessage.toString());
        byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
        DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
                dstAddress);

        // Send multi-cast packet
        MulticastSocket multicast = null;
        try {
            multicast = new MulticastSocket(null);
            multicast.bind(srcAddress);
            logger.trace("Source-Address = '{}'", srcAddress);
            multicast.setTimeToLive(5);
            logger.trace("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        MulticastSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setTimeToLive(10);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    logger.debug("Receive SSDP Message.");
                    receivePacket = new DatagramPacket(new byte[2048], 2048);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    if (message.contains("Belkin")) {
                        logger.trace("Received message: {}", message);
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (message != null) {
                                String location = StringUtils.substringBetween(message, "LOCATION: ",
                                        "/setup.xml");
                                String udn = StringUtils.substringBetween(message, "USN: uuid:",
                                        "::urn:Belkin");
                                if (udn != null) {
                                    logger.trace("Save location '{}' for WeMo device with UDN '{}'", location,
                                            udn);
                                    wemoConfigMap.put(udn, location);
                                    logger.info("Wemo Device with UDN '{}' discovered", udn);
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    for (String name : wemoConfigMap.keySet()) {
                        logger.trace(name + ":" + wemoConfigMap.get(name));
                    }
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not start wemo device discovery", e);
    }

}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;/*from  w  w w.  j av a2s .co m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final String multicastAddress = this.multicastRule.getGroup();
    final String payload = "foo";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch received = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[8];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[length];
            System.arraycopy(src, offset, dest, 0, length);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            received.countDown();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.afterPropertiesSet();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(received.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}