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:MainClass.java

public static void main(String[] args) throws Exception {

    int port = 0;
    byte ttl = (byte) 1;

    InetAddress ia = InetAddress.getByName("127.0.0.1");

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

    MulticastSocket ms = new MulticastSocket();
    ms.joinGroup(ia);/*ww  w  .jav a2s.  c o  m*/
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);
    }
    ms.leaveGroup(ia);
    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    int port = 0;
    byte ttl = (byte) 1;

    InetAddress ia = InetAddress.getByName("127.0.0.1");

    byte[] data = "Here's some multicast data\r\n".getBytes();
    DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

    MulticastSocket ms = new MulticastSocket();
    ms.joinGroup(ia);//from   www  . j  a  v a  2s . c om
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);
    }
    ms.leaveGroup(ia);

    ia = ms.getInterface();
    System.out.println(ia);

    ms.close();
}

From source file:MulticastSender.java

public static void main(String[] args) {

    InetAddress ia = null;//from   w  ww.  j  a va 2  s .c o  m
    int port = 0;
    String characters = "Here's some multicast data\n";
    byte[] data = new byte[characters.length()];

    // read the address from the command line
    try {
        try {
            ia = InetAddress.getByName(args[0]);
        } catch (UnknownHostException e) {
            //ia = InetAddressFactory.newInetAddress(args[0]);
        }
        port = Integer.parseInt(args[1]);
    } catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java MulticastSender MulticastAddress port");
        System.exit(1);
    }

    characters.getBytes(0, characters.length(), data, 0);
    DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

    try {
        MulticastSocket ms = new MulticastSocket();
        ms.joinGroup(ia);
        for (int i = 1; i < 10; i++) {
            ms.send(dp, (byte) 1);
        }
        ms.leaveGroup(ia);
        ms.close();
    } catch (SocketException se) {
        System.err.println(se);
    } catch (IOException ie) {
        System.err.println(ie);
    }

}

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

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;/*  w  w w .  ja v  a2  s  .c om*/
    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();
}

From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.discovery.UDPDiscoverySender.java

/**
 * Constructor for the UDPDiscoverySender object
 * <p>/*  ww w  .ja  v  a2s  .c  om*/
 * This sender can be used to send multiple messages.
 * <p>
 * When you are done sending, you should destroy the socket sender.
 *
 * @param host
 * @param port
 *
 * @exception IOException
 */
public UDPDiscoverySender(String host, int port) throws IOException {
    try {
        m_localSocket = new MulticastSocket();

        // Remote address.
        m_multicastAddress = InetAddress.getByName(host);
    } catch (IOException e) {
        log.error("Could not bind to multicast address [" + host + "]", e);

        throw e;
    }

    m_multicastPort = port;
}

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

private String checkMulticast() throws Exception {
    String nic = SocketTestUtils.chooseANic(true);
    if (nic == null) { // no multicast support
        this.skip = true;
        return null;
    }/*from w  w w.j  a v a2s .  c  om*/
    try {
        MulticastSocket socket = new MulticastSocket();
        socket.joinGroup(InetAddress.getByName(this.group));
        socket.close();
    } catch (Exception e) {
        this.skip = true;
        // Ignore. Assume no Multicast - skip the test.
    }
    return nic;
}

From source file:org.apache.jcs.auxiliary.lateral.socket.udp.LateralUDPSender.java

/**
 * Constructor for the LateralUDPSender object
 *
 * @param lca/*from  w ww .  j  ava2  s  .c  o  m*/
 * @exception IOException
 */
public LateralUDPSender(ILateralCacheAttributes lca) throws IOException {
    this.ilca = lca;

    try {

        m_localSocket = new MulticastSocket();

        // Remote address.
        m_multicastAddress = InetAddress.getByName(lca.getUdpMulticastAddr());
    } catch (IOException e) {
        log.error("Could not bind to multicast address " + lca.getUdpMulticastAddr(), e);

        throw e;
    }

    m_multicastPort = lca.getUdpMulticastPort();
}

From source file:net.sf.jinsim.UDPChannel.java

/**
 * Construct a Receiver that is ready to communicate with a LFS server at a particular address.
 * /*from  w  w  w . j a v a  2 s  . c o m*/
 * @param channel
 *            The DatagramChannel that the communication will take place on.
 * @param address
 *            A network address to send acknowledgement (ACK) packets to.
 * @param multicast
 *            Receiver will relay the packets received to a multicast address if multicast is true.
 * @throws IOException
 */
public UDPChannel(InetSocketAddress address, boolean multicast) throws IOException {
    super();

    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.socket().bind(null);
    //datagramChannel.connect(address);
    this.address = address;

    if (multicast) {
        InetAddress group = InetAddress.getByName("223.223.223.223");
        multicastSocket = new MulticastSocket();
        multicastSocket.joinGroup(group);
    }

}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

/**
 * Constructs a new instance of this class.
 *//* ww  w . j a  v a 2  s . co m*/
private SsdpHandler() {
    LOG.info("Instantiating SsdpHandler");

    try {
        // Use first IPv4 address that isn't loopback, any, or link local as the server address
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && serverAddress == null) {
            NetworkInterface i = interfaces.nextElement();
            Enumeration<InetAddress> addresses = i.getInetAddresses();
            while (addresses.hasMoreElements() && serverAddress == null) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
                        serverAddress = address;
                    }
                }
            }
        }

        if (serverAddress == null) {
            LOG.warn("Server address unknown");
        }

        svc = SsdpService.forAllMulticastAvailableNetworkInterfaces(this);
        svc.listen();

        // setup Multicast for Notify messages
        notifySocket = new MulticastSocket();
        notifySocket.setTimeToLive(TTL);
        notifyTimer = new Timer("UPnP Notify Timer", true);
        notifyTimer.scheduleAtFixedRate(new NotifySender(), 5000, MAX_AGE * 1000 / 2);
    } catch (Exception e) {
        LOG.error("SsdpHandler in unknown state due to exception in constructor.", e);
    }
}

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  a  2s  . c  om
 */
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();
}