Example usage for java.net MulticastSocket MulticastSocket

List of usage examples for java.net MulticastSocket MulticastSocket

Introduction

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

Prototype

public MulticastSocket() throws IOException 

Source Link

Document

Create a multicast socket.

Usage

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/*from   ww  w .  j ava 2s  .co  m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            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[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } 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,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java

private void setupSocket() {
    try {//w  w  w.jav  a2 s  . c  o  m
        socket = new MulticastSocket(); // must bind receive side
        socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
    } catch (IOException e) {
        logger.error(e.toString());
    }

    thread = new Thread(new Runnable() {
        public void run() {
            receiveData(socket, dgram);
        }
    });
    thread.start();
}

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 w  w w . jav  a  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);
    }

}

From source file:org.lwes.emitter.MulticastEventEmitter.java

/**
 * Initializes the emitter./*w  w w  .java 2  s.com*/
 */
@Override
public void initialize() throws IOException {
    socket = new MulticastSocket();

    if (iface != null) {
        socket.setInterface(iface);
    }

    socket.setTimeToLive(ttl);
    super.initialize();
}

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

/**
 * Discovery Process to identify Clusters with in 
 * network./*from   ww w  .  j  a v a2s  . 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:net.sf.ehcache.distribution.MulticastRMIPeerProviderTest.java

/**
 * Determines that the multicast TTL default is 1, which means that packets are restricted to the same subnet.
 * peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, multicastPacketTimeToLive=255
 *//*  w ww.j a va  2s  .  com*/
public void testMulticastTTL() throws IOException {
    InetAddress groupAddress = InetAddress.getByName("230.0.0.1");
    MulticastSocket socket = new MulticastSocket();
    socket.joinGroup(groupAddress);
    int ttl = socket.getTimeToLive();
    assertEquals(1, ttl);
}

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.//from  ww w.  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:com.all.landownloader.discovery.LanDiscoverySocket.java

private void announce() throws IllegalArgumentException {
    try {/*  ww  w  .j  a  v  a2  s . co m*/
        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:com.all.landownloader.discovery.LanDiscoverySocket.java

public void announceDeath() throws IllegalArgumentException {
    try {/*  w w w .  ja  va2 s  .  co  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) {
    }
}