Example usage for java.net MulticastSocket send

List of usage examples for java.net MulticastSocket send

Introduction

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

Prototype

public void send(DatagramPacket p) throws IOException 

Source Link

Document

Sends a datagram packet from this socket.

Usage

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Discovery Process to identify Clusters with in 
 * network./*from  w w  w  . j  ava2  s  .  c  o  m*/
 * 
 * @throws IOException if occurred during operation
 */
private void doDiscover() throws IOException {

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Wait for Response
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Receive
    resSock.setSoTimeout((int) TIMEOUT);
    try {
        resSock.receive(response);
    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    }

    byte[] data = response.getData();

    byte[] ipBytes = Arrays.copyOfRange(data, 0, 4);
    byte[] portBytes = Arrays.copyOfRange(data, 4, 9);

    InetAddress ip = InetAddress.getByAddress(ipBytes);
    StringBuilder sb = new StringBuilder(ip.getHostAddress());
    sb.append(":");
    for (byte b : portBytes) {
        sb.append(b);
    }

    this.cluster = sb.toString();
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Attempts to discover peer clusters using Multicast
 * Discovery. Each discovered Cluster will be notified
 * to the {@code PeerClusterService} of the 
 * ClusterManager./* w  ww  . j  a v  a  2 s  .  c o m*/
 * 
 * @throws IOException if occurred during process
 */
public static void discoverPeerClusters() throws IOException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    log.info("[MulticastDiscovery] Discovering Peer Clusters...");

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Response Socket
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Set Socket Timeout
    resSock.setSoTimeout((int) TIMEOUT);

    try {

        // Loop until Socket Timeout Occurs
        while (true) {

            // Receive
            resSock.receive(response);
            processPeerResponse(response.getData());

        }

    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    } finally {
        log.info("[MulticastDiscovery] Peer Cluster Discovery Complete");
    }

}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Broadcasts a SSDP discovery message into the network to find provided
 * services./* w ww.j  av  a  2 s . co  m*/
 * 
 * @return The Socket the answers will arrive at.
 * @throws UnknownHostException
 * @throws IOException
 * @throws SocketException
 * @throws UnsupportedEncodingException
 */
private MulticastSocket sendDiscoveryBroacast()
        throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
    InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
    final int port = 1900;
    MulticastSocket socket = new MulticastSocket(port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(130000);
    socket.joinGroup(multicastAddress);
    byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
            port);
    socket.send(datagramPacket);
    return socket;
}

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

public void wemoDiscovery() {
    logger.debug("wemoDiscovery() is called!");
    try {//from ww w  .  j  a v  a 2  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);
    }

}