Search in sources :

Example 6 with MulticastSocket

use of java.net.MulticastSocket in project quickstarts by jboss-switchyard.

the class CamelNettyBindingTest method sendTextMessageThroughUdp.

@Test
public void sendTextMessageThroughUdp() throws Exception {
    // replace existing implementation for testing purposes
    _testKit.removeService("DefaultGreetingService");
    final MockHandler greetingService = _testKit.registerInOnlyService("DefaultGreetingService");
    MulticastSocket clientSocket = new MulticastSocket();
    InetAddress group = InetAddress.getByName("localhost");
    byte[] datagramBody = PAYLOAD.getBytes(Charset.defaultCharset());
    DatagramPacket packet = new DatagramPacket(datagramBody, 0, datagramBody.length, group, 3940);
    clientSocket.send(packet);
    // sleep a bit to receive message on camel side
    clientSocket.close();
    greetingService.waitForOKMessage();
    final LinkedBlockingQueue<Exchange> recievedMessages = greetingService.getMessages();
    assertThat(recievedMessages, is(notNullValue()));
    final Exchange recievedExchange = recievedMessages.iterator().next();
    String content = recievedExchange.getMessage().getContent(String.class);
    // the receive content is trimmed because extra bytes appended to frame by receiver
    assertThat(PAYLOAD, is(equalTo(content.trim())));
}
Also used : Exchange(org.switchyard.Exchange) MulticastSocket(java.net.MulticastSocket) DatagramPacket(java.net.DatagramPacket) MockHandler(org.switchyard.test.MockHandler) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Example 7 with MulticastSocket

use of java.net.MulticastSocket in project openhab1-addons by openhab.

the class SsdpDiscovery method setUpSocket.

private static MulticastSocket setUpSocket() throws IOException {
    MulticastSocket recSocket = new MulticastSocket(null);
    recSocket.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), PORT));
    recSocket.setTimeToLive(10);
    recSocket.setSoTimeout(1000);
    recSocket.setBroadcast(true);
    return recSocket;
}
Also used : MulticastSocket(java.net.MulticastSocket) InetSocketAddress(java.net.InetSocketAddress)

Example 8 with MulticastSocket

use of java.net.MulticastSocket in project openhab1-addons by openhab.

the class SsdpDiscovery method sendNotify.

private static void sendNotify(String notifyMessage, InetAddress ia) throws Exception {
    MulticastSocket socket = new MulticastSocket(null);
    try {
        socket.bind(new InetSocketAddress(PORT));
        socket.setTimeToLive(4);
        byte[] data = notifyMessage.toString().getBytes();
        socket.send(new DatagramPacket(data, data.length, new InetSocketAddress(ia, PORT)));
    } catch (Exception e) {
        logger.error("sendNotify", e);
        throw e;
    } finally {
        socket.disconnect();
        socket.close();
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException)

Example 9 with MulticastSocket

use of java.net.MulticastSocket in project openhab1-addons by openhab.

the class SsdpDiscovery method retrieveResponse.

static Map<String, Map<String, String>> retrieveResponse() throws Exception {
    String response = null;
    Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
    MulticastSocket recSocket = setUpSocket();
    int i = 0;
    logger.debug("Retrieving response");
    while (i < 10) {
        byte[] buf = new byte[2048];
        DatagramPacket input = new DatagramPacket(buf, buf.length);
        try {
            recSocket.receive(input);
            response = new String(input.getData());
            Map<String, String> parsedResponse = parseResponse(response);
            result.put(parsedResponse.get("IP"), parsedResponse);
        } catch (SocketTimeoutException e) {
            if (i >= 10) {
                break;
            }
            i++;
        }
    }
    logger.debug("Response retrieved: {}", result);
    return result;
}
Also used : MulticastSocket(java.net.MulticastSocket) SocketTimeoutException(java.net.SocketTimeoutException) HashMap(java.util.HashMap) DatagramPacket(java.net.DatagramPacket) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with MulticastSocket

use of java.net.MulticastSocket in project openhab1-addons by openhab.

the class WemoBinding method wemoDiscovery.

public void wemoDiscovery() {
    logger.debug("wemoDiscovery() is called!");
    try {
        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);
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(java.net.DatagramPacket) InetAddress(java.net.InetAddress) ConfigurationException(org.osgi.service.cm.ConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Aggregations

MulticastSocket (java.net.MulticastSocket)48 IOException (java.io.IOException)18 DatagramPacket (java.net.DatagramPacket)18 InetSocketAddress (java.net.InetSocketAddress)15 InetAddress (java.net.InetAddress)14 DatagramSocket (java.net.DatagramSocket)10 Test (org.junit.Test)10 SocketException (java.net.SocketException)7 SocketTimeoutException (java.net.SocketTimeoutException)7 UnknownHostException (java.net.UnknownHostException)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 NetworkInterface (java.net.NetworkInterface)4 SocketAddress (java.net.SocketAddress)4 SubsetConfiguration (org.apache.commons.configuration2.SubsetConfiguration)4 ConfigBuilder (org.apache.hadoop.metrics2.impl.ConfigBuilder)4 URI (java.net.URI)3 ArrayList (java.util.ArrayList)3 Timer (java.util.Timer)3 ReentrantLock (java.util.concurrent.locks.ReentrantLock)3 BindException (java.net.BindException)2