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:net.sbbi.upnp.Discovery.java

/**
 * Sends an SSDP search message on the network
 * @param src the sender ip//  w w  w . ja v a  2s.  co  m
 * @param ttl the time to live
 * @param mx the mx field
 * @param searchTarget the search target
 * @throws IOException if some IO errors occurs during search
 */
public static void sendSearchMessage(InetAddress src, int ttl, int mx, String searchTarget) throws IOException {

    int bindPort = DEFAULT_SSDP_SEARCH_PORT;
    String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort");
    if (port != null) {
        bindPort = Integer.parseInt(port);
    }
    InetSocketAddress adr = new InetSocketAddress(InetAddress.getByName(Discovery.SSDP_IP),
            Discovery.SSDP_PORT);

    java.net.MulticastSocket skt = new java.net.MulticastSocket(null);
    skt.bind(new InetSocketAddress(src, bindPort));
    skt.setTimeToLive(ttl);
    StringBuffer packet = new StringBuffer();
    packet.append("M-SEARCH * HTTP/1.1\r\n");
    packet.append("HOST: 239.255.255.250:1900\r\n");
    packet.append("MAN: \"ssdp:discover\"\r\n");
    packet.append("MX: ").append(mx).append("\r\n");
    packet.append("ST: ").append(searchTarget).append("\r\n").append("\r\n");
    if (log.isDebugEnabled())
        log.debug("Sending discovery message on 239.255.255.250:1900 multicast address form ip "
                + src.getHostAddress() + ":\n" + packet.toString());
    String toSend = packet.toString();
    byte[] pk = toSend.getBytes();
    skt.send(new DatagramPacket(pk, pk.length, adr));
    skt.disconnect();
    skt.close();
}

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

public void announceDeath() throws IllegalArgumentException {
    try {/*from   w w w  . ja v  a 2 s  .c  o  m*/
        byte[] buf = createPacket(BYE_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addressGroup, PORT);
        MulticastSocket socket = new MulticastSocket();
        socket.send(packet);
        packet = new DatagramPacket(buf, buf.length, broadcast, PORT);
        socket.send(packet);
        socket.close();
    } catch (IOException e) {
    }
}

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

private void announce() throws IllegalArgumentException {
    try {/*from w  ww .  j  ava 2 s .c  om*/
        byte[] buf = createPacket(ANNOUNCE_MSG);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, addressGroup, PORT);
        MulticastSocket socket = new MulticastSocket();
        socket.send(packet);
        packet = new DatagramPacket(buf, buf.length, broadcast, PORT);
        socket.send(packet);
        socket.close();
    } catch (Exception e) {
    }

}

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));
    }//www .j av  a 2s . c  o  m
    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  ww .  jav  a2 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/* w ww.  jav  a2 s.  com*/
 */
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;/*from   w w w. j  a  v a 2 s. c  o  m*/
    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:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
 * Send a SSDP search message with the given search target (ST) and return a list of received responses.
 *//* w  ww .jav  a2  s.  com*/
public Map<String, URL> discover(String searchTarget) {
    Log.d("HUE", "ServiceDiscovery.discover");
    final InetSocketAddress address;
    // standard multicast port for SSDP
    try {
        // multicast address with administrative scope
        address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
        //address = InetAddress.getByName(MULTICAST_ADDRESS);

    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not get multicast address", e);
    }

    final MulticastSocket socket;
    try {
        socket = new MulticastSocket(null);

        InetAddress localhost = getAndroidLocalIP();

        InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT);
        Log.d("HUE", "" + srcAddress.getAddress());
        socket.bind(srcAddress);
        Log.d("HUE", "step 1");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not create multicast socket");
    }

    try {
        socket.setSoTimeout(socketTimeout);
        Log.d("HUE", "step 2");
    } catch (SocketException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set socket timeout", e);
    }

    try {
        socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
        Log.d("HUE", "step 3");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e);
    }
    try {
        socket.setTimeToLive(ttl);
        Log.d("HUE", "step 4");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set TTL " + ttl, e);
    }
    final byte[] transmitBuffer;
    try {
        transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME);
        Log.d("HUE", "step 5");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e);
    }
    DatagramPacket packet = null;
    try {
        packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address);
        Log.d("HUE", "step 6");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.send(packet);
        Log.d("HUE", "step 7");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not send search request", e);
    }
    Map<String, URL> result = new HashMap<String, URL>();
    byte[] receiveBuffer = new byte[1536];
    while (true) {
        try {
            Log.d("HUE", "sending packets");
            final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length,
                    InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
            socket.receive(receivePacket);
            //Log.d("HUE", new String(receivePacket.getData()));
            HueBridge response = parseResponsePacket(receivePacket);
            if (response != null) {
                Log.d("HUE", "resonse not null");
                ////System.out.println("resonse not null");
                result.put(response.getUDN(), response.getBaseUrl());
            } else {
                Log.d("HUE", "no bridge");
            }
        } catch (SocketTimeoutException e) {
            Log.e("HUE", "timeout exception");
            break;
        } catch (IOException e) {
            throw new IllegalStateException("Problem receiving search responses", e);
        }
    }
    return result;
}

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

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {// w ww  .j a  v a 2 s  . c om

        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.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Responds  to a Multicast Discovery Request by publishing
 * the IP Address of Service into response channel. 
 *///from ww w .j a va  2s  .c o  m
protected static void doRespond() {

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

    try {
        // Get Broker Service URL
        String serviceUrl = ClusterManager.getInstance().getClusterInfo().getServiceUrl();

        byte[] hostInfo = NetUtils.getHostInfoAsBytes(serviceUrl);

        // Create Response Packet
        DatagramPacket response = new DatagramPacket(hostInfo, hostInfo.length, SERVICE_RESPONSE_IP,
                SERVICE_PORT);

        // Create Multicast Socket
        MulticastSocket resSock = new MulticastSocket();

        // Send response
        resSock.send(response);

        log.debug("[MulticastDiscovery] Responded Discovery Request");
    } catch (Exception e) {
        log.error("[MulticastDiscovery] Service Failed to Reply", e);
    }

}