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(InetAddress mcastaddr) throws IOException 

Source Link

Document

Joins a multicast group.

Usage

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(InetSocketAddress.createUnresolved("java2s.com", 8080));
    ms.joinGroup(ia);
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);//from  ww w  .  j av  a  2s.  co  m
    }
    ms.leaveGroup(ia);

    System.out.println(ms.getNetworkInterface().getDisplayName());

    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(InetSocketAddress.createUnresolved("java2s.com", 8080));
    ms.joinGroup(ia);
    for (int i = 1; i < 10; i++) {
        ms.send(dp, ttl);/*from  w w w.  j a va2  s  .c o  m*/
    }
    ms.leaveGroup(ia);

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

    ms.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int mcPort = 12345;
    String mcIPStr = "230.1.1.1";
    MulticastSocket mcSocket = null;
    InetAddress mcIPAddress = null;
    mcIPAddress = InetAddress.getByName(mcIPStr);
    mcSocket = new MulticastSocket(mcPort);
    System.out.println("Multicast Receiver running at:" + mcSocket.getLocalSocketAddress());
    mcSocket.joinGroup(mcIPAddress);

    DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

    System.out.println("Waiting for a  multicast message...");
    mcSocket.receive(packet);//from  w ww  .ja  va  2 s . c o  m
    String msg = new String(packet.getData(), packet.getOffset(), packet.getLength());
    System.out.println("[Multicast  Receiver] Received:" + msg);

    mcSocket.leaveGroup(mcIPAddress);
    mcSocket.close();
}

From source file:MulticastClient.java

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

   MulticastSocket socket = new MulticastSocket(4446);
   InetAddress address = InetAddress.getByName("230.0.0.1");
   socket.joinGroup(address);

   DatagramPacket packet;//from   ww  w.j  a  va 2 s  . c om

   // get a few quotes
   for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData());
      System.out.println("Quote of the Moment: " + received);
   }

   socket.leaveGroup(address);
   socket.close();
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send alive.//from w w w .ja va 2 s . co  m
 */
public static void sendAlive() {
    logger.debug("Sending ALIVE...");
    MulticastSocket multicastSocket = null;

    try {
        multicastSocket = getNewMulticastSocket();
        InetAddress upnpAddress = getUPNPAddress();
        multicastSocket.joinGroup(upnpAddress);

        sendMessage(multicastSocket, "upnp:rootdevice", ALIVE);
        sendMessage(multicastSocket, PMS.get().usn(), ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:device:MediaServer:1", ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ContentDirectory:1", ALIVE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ConnectionManager:1", ALIVE);
    } catch (IOException e) {
        logger.debug("Error sending ALIVE message", e);
    } finally {
        if (multicastSocket != null) {
            // Clean up the multicast socket nicely
            try {
                InetAddress upnpAddress = getUPNPAddress();
                multicastSocket.leaveGroup(upnpAddress);
            } catch (IOException e) {
            }

            multicastSocket.disconnect();
            multicastSocket.close();
        }
    }
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send the UPnP BYEBYE message.//from  ww w  .j  a  v  a 2s.c  om
 */
public static void sendByeBye() {
    logger.info("Sending BYEBYE...");

    MulticastSocket multicastSocket = null;

    try {
        multicastSocket = getNewMulticastSocket();
        InetAddress upnpAddress = getUPNPAddress();
        multicastSocket.joinGroup(upnpAddress);

        sendMessage(multicastSocket, "upnp:rootdevice", BYEBYE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:device:MediaServer:1", BYEBYE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ContentDirectory:1", BYEBYE);
        sendMessage(multicastSocket, "urn:schemas-upnp-org:service:ConnectionManager:1", BYEBYE);
    } catch (IOException e) {
        logger.debug("Error sending BYEBYE message", e);
    } finally {
        if (multicastSocket != null) {
            // Clean up the multicast socket nicely
            try {
                InetAddress upnpAddress = getUPNPAddress();
                multicastSocket.leaveGroup(upnpAddress);
            } catch (IOException e) {
            }

            multicastSocket.disconnect();
            multicastSocket.close();
        }
    }
}

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  v a2  s  .c om*/
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:com.all.landownloader.discovery.LanDiscoverySocket.java

public LanDiscoveredPeer listen() throws IOException, IllegalArgumentException {
    MulticastSocket socket = new MulticastSocket(PORT);
    socket.joinGroup(addressGroup);
    byte[] buf = new byte[BUF_LENGTH];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);/* w w w  .j a va2 s . c om*/
    socket.leaveGroup(addressGroup);
    socket.close();

    InetAddress address = packet.getAddress();
    byte[] remotePortBuffer = new byte[4];
    System.arraycopy(buf, HEADER_LENGTH, remotePortBuffer, 0, remotePortBuffer.length);
    LanDiscoveredPeer discoveredPeer = new LanDiscoveredPeer(address, LanUtils.decodeInt(remotePortBuffer));

    if (eq(BYE_MSG, buf, HEADER_LENGTH)) {
        addresses.remove(address);
        RegisteredAddress remove = quickLeases.remove(address);
        if (remove != null) {
            leases.remove(remove);
        }
        return null;
    }

    RegisteredAddress reg = quickLeases.get(discoveredPeer);
    long nextLeaseTime = System.currentTimeMillis() + this.leaseTime;
    if (reg == null) {
        reg = new RegisteredAddress(nextLeaseTime, discoveredPeer);
        quickLeases.put(discoveredPeer, reg);
    } else {
        reg.setLease(nextLeaseTime);
    }
    if (eq(ANNOUNCE_MSG, buf, HEADER_LENGTH)) {
        reply(address);
    }
    leases.add(reg);
    addresses.add(discoveredPeer);
    return discoveredPeer;
}

From source file:Reflector.java

private MulticastSocket initMulticastSocket() {
    // initialize a MulticastSocket and join the group

    MulticastSocket mc;
    try {//  ww  w .ja  va 2s. c om
        mc = new MulticastSocket(listenPort);
        mc.joinGroup(listenAddr);
    } catch (Exception e) {
        System.err.println("Failed to create MulticastSocket on " + "port " + listenPort);
        return (null);
    }
    return (mc);
}

From source file:ws.argo.Responder.Responder.java

public void run() throws IOException, ClassNotFoundException {

    ArrayList<ProbeHandlerPluginIntf> handlers = new ArrayList<ProbeHandlerPluginIntf>();

    // load up the handler classes specified in the configuration parameters
    // I hope the hander classes are in a jar file on the classpath
    handlers = loadHandlerPlugins(cliValues.config.appHandlerConfigs);

    @SuppressWarnings("resource")
    MulticastSocket socket = new MulticastSocket(cliValues.config.multicastPort);
    address = InetAddress.getByName(cliValues.config.multicastAddress);
    LOGGER.info("Starting Responder on " + address.toString() + ":" + cliValues.config.multicastPort);
    socket.joinGroup(address);

    DatagramPacket packet;//  w ww . j  a v  a 2s . c  om
    ResponsePayloadBean response = null;

    LOGGER.info(
            "Responder started on " + cliValues.config.multicastAddress + ":" + cliValues.config.multicastPort);

    httpClient = HttpClients.createDefault();

    LOGGER.fine("Starting Responder loop - infinite until process terminated");
    // infinite loop until the responder is terminated
    while (true) {

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        LOGGER.fine("Waiting to recieve packet...");
        socket.receive(packet);

        LOGGER.fine("Received packet");
        LOGGER.fine("Packet contents:");
        // Get the string
        String probeStr = new String(packet.getData(), 0, packet.getLength());
        LOGGER.fine("Probe: \n" + probeStr);

        try {
            ProbePayloadBean payload = parseProbePayload(probeStr);

            LOGGER.info("Received probe id: " + payload.probeID);

            // Only handle probes that we haven't handled before
            // The Probe Generator needs to send a stream of identical UDP packets
            // to compensate for UDP reliability issues.  Therefore, the Responder
            // will likely get more than 1 identical probe.  We should ignore duplicates.
            if (!handledProbes.contains(payload.probeID)) {
                for (ProbeHandlerPluginIntf handler : handlers) {
                    response = handler.probeEvent(payload);
                    sendResponse(payload.respondToURL, payload.respondToPayloadType, response);
                }
                handledProbes.add(payload.probeID);
            } else {
                LOGGER.info("Discarding duplicate probe with id: " + payload.probeID);
            }

        } catch (SAXException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

    }

}