Example usage for java.net MulticastSocket joinGroup

List of usage examples for java.net MulticastSocket joinGroup

Introduction

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

Prototype

public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException 

Source Link

Document

Joins the specified multicast group at the specified interface.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*  w ww .  ja  va 2  s. co m*/
    }
    ms.leaveGroup(InetAddress.getByName("google.com"));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*from  www .  ja  v a  2s.co  m*/
    }
    ms.setLoopbackMode(true);

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from w w w . j  a  v a2s.com
    }
    ms.setNetworkInterface(NetworkInterface.getByIndex(0));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//  w ww. j  a va  2 s . com
    }
    ms.setTimeToLive(1000);

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from w w  w.  j  av  a  2s.c  o  m
    }
    ms.leaveGroup(InetSocketAddress.createUnresolved("java2s.com", 8080), NetworkInterface.getByIndex(0));

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int port = 0;
    byte ttl = (byte) 1;

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

    MulticastSocket ms = new MulticastSocket(InetSocketAddress.createUnresolved("google.com", 8080));
    ms.joinGroup(InetSocketAddress.createUnresolved("127.0.0.1", 8080), NetworkInterface.getByIndex(0));
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from  ww w.  j  a v a  2 s. c  o m
    }
    ms.setInterface(InetAddress.getByName("google.com"));

    ms.close();
}

From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java

/**
 * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called.
 * @param listener listener to notify of events
 * @throws IOException if socket error occurs
 * @throws NullPointerException if any argument is {@code null}
 *///from ww  w  .jav  a  2 s.c o  m
public void start(NatPmpEventListener listener) throws IOException {
    Validate.notNull(listener);

    MulticastSocket socket = null;
    try {
        final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD
        final int port = 5350;
        final InetSocketAddress groupAddress = new InetSocketAddress(group, port);

        socket = new MulticastSocket(port);

        if (!currentSocket.compareAndSet(null, socket)) {
            IOUtils.closeQuietly(socket);
            return;
        }

        socket.setReuseAddress(true);

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                try {
                    if (addr instanceof Inet4Address) {
                        socket.joinGroup(groupAddress, networkInterface);
                    }
                } catch (IOException ioe) { // NOPMD
                    // occurs with certain interfaces
                    // do nothing
                }
            }
        }

        ByteBuffer buffer = ByteBuffer.allocate(12);
        DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity());

        while (true) {
            buffer.clear();
            socket.receive(data);
            buffer.position(data.getLength());
            buffer.flip();

            if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore
                continue;
            }

            if (buffer.remaining() != 12) { // data isn't the expected size, ignore
                continue;
            }

            int version = buffer.get(0);
            if (version != 0) { // data doesn't have the correct version, ignore
                continue;
            }

            int opcode = buffer.get(1) & 0xFF;
            if (opcode != 128) { // data doesn't have the correct op, ignore
                continue;
            }

            int resultCode = buffer.getShort(2) & 0xFFFF;
            switch (resultCode) {
            case 0:
                break;
            default:
                continue; // data doesn't have a successful result, ignore
            }

            listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer));
        }

    } catch (IOException ioe) {
        if (currentSocket.get() == null) {
            return; // ioexception caused by interruption/stop, so just return without propogating error up
        }

        throw ioe;
    } finally {
        IOUtils.closeQuietly(socket);
        currentSocket.set(null);
    }
}

From source file:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {//from  www . j a  v a2s . c  o  m
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}