Java Code Examples for java.net.MulticastSocket

The following examples show how to use java.net.MulticastSocket. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Tomcat8-Source-Read   Source File: TesterMulticast.java    License: MIT License 6 votes vote down vote up
@Override
public void run() {
    try (MulticastSocket s = new MulticastSocket(PORT)) {
        s.setLoopbackMode(false);
        s.joinGroup(INET_ADDRESS);
        DatagramPacket p = new DatagramPacket(new byte[4], 4);
        p.setAddress(INET_ADDRESS);
        p.setPort(PORT);
        long counter = 0;
        String msg;
        while (run) {
            msg = String.format("%04d", Long.valueOf(counter));
            p.setData(msg.getBytes());
            System.out.println("Tx: " + msg);
            s.send(p);
            counter++;
            Thread.sleep(500);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Source Project: commons-jcs   Source File: UDPDiscoverySender.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for the UDPDiscoverySender object
 * <p>
 * This sender can be used to send multiple messages.
 * <p>
 * When you are done sending, you should destroy the socket sender.
 * <p>
 * @param host
 * @param port
 * @param udpTTL the Datagram packet time-to-live
 * @throws IOException
 */
public UDPDiscoverySender( String host, int port, int udpTTL )
    throws IOException
{
    try
    {
        log.debug( "Constructing socket for sender on port [{0}]", port );
        localSocket = new MulticastSocket( port );
        if (udpTTL > 0)
        {
            log.debug( "Setting datagram TTL to [{0}]", udpTTL );
            localSocket.setTimeToLive(udpTTL);
        }

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

    this.multicastPort = port;
}
 
Example 3
public void sendFrame(final Frame frame) throws IOException {

      final byte[] message = toValidMessage(frame);
      final DatagramPacket packet = new DatagramPacket(message, 0, message.length, mcastAddress, mcastPort);
      for (final MulticastSocket mcastSocket : mcastSockets) {

         try {

            sentMessages++;
            mcastSocket.send(packet);
         } catch (final IOException e) {

            final String exceptionMessage = e.getMessage();
            if (exceptionMessage.endsWith(NO_BUFFER_SPACE_AVAILABLE)
                    || exceptionMessage.endsWith(NO_ROUTE_TO_HOST)) {

               final NetworkInterface networkInterface = mcastSocket.getNetworkInterface();
               final InetAddress mcastSocketInterface = mcastSocket.getInterface();
               LOG.warn(createIgnoredWarning(exceptionMessage, networkInterface, mcastSocketInterface));
            } else {

               throw e;
            }
         }
      }
   }
 
Example 4
Source Project: openbd-core   Source File: MultiCastManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public RxdThread() {
  super("MultiCastManager.RxdThread." + address + "#" + port);
  setDaemon(true);
  
  bReceiving  = true;
  
  try {
    msocket = new MulticastSocket( port );
    msocket.setInterface( bindAddress );
    msocket.joinGroup(groupAddr);
    start();
    
    cfcThread = new cfcRunnerThread();
    
  } catch (IOException e) {
    log( "RxdThread.IOException:" + e.getMessage() );
  }
}
 
Example 5
Source Project: DroidDLNA   Source File: DatagramIOImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
synchronized public void init(InetAddress bindAddress, Router router, DatagramProcessor datagramProcessor) throws InitializationException {

        this.router = router;
        this.datagramProcessor = datagramProcessor;

        try {

            // TODO: UPNP VIOLATION: The spec does not prohibit using the 1900 port here again, however, the
            // Netgear ReadyNAS miniDLNA implementation will no longer answer if it has to send search response
            // back via UDP unicast to port 1900... so we use an ephemeral port
            log.info("Creating bound socket (for datagram input/output) on: " + bindAddress);
            localAddress = new InetSocketAddress(bindAddress, 0);
            socket = new MulticastSocket(localAddress);
            socket.setTimeToLive(configuration.getTimeToLive());
            socket.setReceiveBufferSize(262144); // Keep a backlog of incoming datagrams if we are not fast enough
        } catch (Exception ex) {
            throw new InitializationException("Could not initialize " + getClass().getSimpleName() + ": " + ex);
        }
    }
 
Example 6
Source Project: qpid-jms   Source File: MulticastDiscoveryAgent.java    License: Apache License 2.0 6 votes vote down vote up
public static void trySetNetworkInterface(MulticastSocket mcastSock) throws SocketException {
    List<NetworkInterface> interfaces = findNetworkInterfaces();
    SocketException lastError = null;
    boolean found = false;

    for (NetworkInterface networkInterface : interfaces) {
        try {
            mcastSock.setNetworkInterface(networkInterface);
            LOG.debug("Configured mcast socket {} to network interface {}", mcastSock, networkInterface);
            found = true;
            break;
        } catch (SocketException error) {
            lastError = error;
        }
    }

    if (!found) {
        if (lastError != null) {
            throw lastError;
        } else {
            throw new SocketException("No NetworkInterface available for this socket.");
        }
    }
}
 
Example 7
Source Project: fuchsia   Source File: KNXnetIPRouter.java    License: Apache License 2.0 5 votes vote down vote up
void close(int initiator, String reason, LogLevel level, Throwable t)
{
	if (getState() == CLOSED)
		return;
	try {
		((MulticastSocket) socket).leaveGroup(multicast);
	}
	catch (final IOException e) {
		logger.warn("problem on leaving multicast group", e);
	}
	finally {
		shutdown(initiator, reason, level, t);
	}
}
 
Example 8
Source Project: dubbo-2.6.5   Source File: MulticastRegistryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPort() {
    MulticastRegistry multicastRegistry = new MulticastRegistry(URL.valueOf("multicast://224.5.6.7"));
    try {
        MulticastSocket multicastSocket = multicastRegistry.getMutilcastSocket();
        Assert.assertEquals(1234, multicastSocket.getLocalPort());
    } finally {
        multicastRegistry.destroy();
    }
}
 
Example 9
public static void main(String[] args) throws Exception {

        boolean passed = true;
        try {
            MulticastSocket ms = new MulticastSocket();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface netIf = networkInterfaces.nextElement();
                if (isNetworkInterfaceTestable(netIf)) {
                    printNetIfDetails(netIf);
                    ms.setNetworkInterface(netIf);
                    NetworkInterface msNetIf = ms.getNetworkInterface();
                    if (netIf.equals(msNetIf)) {
                        System.out.println(" OK");
                    } else {
                        System.out.println("FAILED!!!");
                        printNetIfDetails(msNetIf);
                        passed = false;
                    }
                    System.out.println("------------------");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            passed = false;
        }
        if (!passed) {
            throw new RuntimeException("Test Fail");
        }
        System.out.println("Test passed ");
    }
 
Example 10
Source Project: nifi   Source File: MulticastUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(final MulticastSocket socket) {

        if (socket == null) {
            return;
        }

        try {
            socket.close();
        } catch (final Exception ex) {
            logger.debug("Failed to close multicast socket due to: " + ex, ex);
        }

    }
 
Example 11
Source Project: dragonwell8_jdk   Source File: JdpTestCase.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 12
Source Project: netty-4.1.22   Source File: OioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
private static MulticastSocket newSocket() {
    try {
        return new MulticastSocket(null);
    } catch (Exception e) {
        throw new ChannelException("failed to create a new socket", e);
    }
}
 
Example 13
Source Project: openhab1-addons   Source File: SsdpDiscovery.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 14
/**
 * Creates an array of sockets with TTL and network interface set.
 *
 * @param mcastTTL multicast TTL.
 * @return an array of multicast sockets to broadcast on.
 * @throws IOException if I/O error occurred while creating a multicast socket.
 * @noinspection SocketOpenedButNotSafelyClosed, ConstantConditions
 */
private static MulticastSocket[] createSockets(final int mcastTTL) throws IOException {

   Exception lastException = null; // Records last error in case we could not create any sockets
   final List<MulticastSocket> socketList = new ArrayList<MulticastSocket>(11);
   final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
   while (enumeration.hasMoreElements()) {
      try {
         final NetworkInterface netIf = enumeration.nextElement();
         if (netIf.supportsMulticast()) {

            final MulticastSocket socket = new MulticastSocket(); // NOPMD
            socket.setTimeToLive(mcastTTL);
            socket.setNetworkInterface(netIf);
            socket.setSendBufferSize(SEND_BUFFER_SIZE);
            socketList.add(socket);
         }
      } catch (final Exception e) {

         lastException = e;
         ExceptionUtils.ignoreException(e, "continue to connect to those we can");
      }
   }
   if (socketList.isEmpty()) {
      throw new IOException("Could not create at least one multicast socket. Last error: " + lastException);
   }
   return socketList.toArray(new MulticastSocket[socketList.size()]);
}
 
Example 15
Source Project: netty-4.1.22   Source File: DefaultDatagramChannelConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatagramChannelConfig setInterface(InetAddress interfaceAddress) {
    if (javaSocket instanceof MulticastSocket) {
        try {
            ((MulticastSocket) javaSocket).setInterface(interfaceAddress);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    } else {
        throw new UnsupportedOperationException();
    }
    return this;
}
 
Example 16
Source Project: gemfirexd-oss   Source File: UDP.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param interfaces List<NetworkInterface>. Guaranteed to have no duplicates
 * @param s
 * @param mcastAddr
 * @throws IOException
 */
private void bindToInterfaces(List interfaces, MulticastSocket s, InetAddress mcastAddr) throws IOException {
    SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
    for(Iterator it=interfaces.iterator(); it.hasNext();) {
        NetworkInterface i=(NetworkInterface)it.next();
        for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr=(InetAddress)en2.nextElement();
            s.joinGroup(tmp_mcast_addr, i);
            if(trace)
                log.trace("joined " + tmp_mcast_addr + " on " + i.getName() + " (" + addr + ")");
            break;
        }
    }
}
 
Example 17
Source Project: netty-4.1.22   Source File: DefaultDatagramChannelConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatagramChannelConfig setLoopbackModeDisabled(boolean loopbackModeDisabled) {
    if (javaSocket instanceof MulticastSocket) {
        try {
            ((MulticastSocket) javaSocket).setLoopbackMode(loopbackModeDisabled);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    } else {
        throw new UnsupportedOperationException();
    }
    return this;
}
 
Example 18
Source Project: netty-4.1.22   Source File: DefaultDatagramChannelConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatagramChannelConfig setNetworkInterface(NetworkInterface networkInterface) {
    if (javaSocket instanceof MulticastSocket) {
        try {
            ((MulticastSocket) javaSocket).setNetworkInterface(networkInterface);
        } catch (SocketException e) {
            throw new ChannelException(e);
        }
    } else {
        throw new UnsupportedOperationException();
    }
    return this;
}
 
Example 19
Source Project: netty-4.1.22   Source File: DefaultDatagramChannelConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatagramChannelConfig setTimeToLive(int ttl) {
    if (javaSocket instanceof MulticastSocket) {
        try {
            ((MulticastSocket) javaSocket).setTimeToLive(ttl);
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    } else {
        throw new UnsupportedOperationException();
    }
    return this;
}
 
Example 20
public static void main(String[] args) throws Exception {

        boolean passed = true;
        try {
            MulticastSocket ms = new MulticastSocket();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface netIf = networkInterfaces.nextElement();
                if (isNetworkInterfaceTestable(netIf)) {
                    printNetIfDetails(netIf);
                    ms.setNetworkInterface(netIf);
                    NetworkInterface msNetIf = ms.getNetworkInterface();
                    if (netIf.equals(msNetIf)) {
                        System.out.println(" OK");
                    } else {
                        System.out.println("FAILED!!!");
                        printNetIfDetails(msNetIf);
                        passed = false;
                    }
                    System.out.println("------------------");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            passed = false;
        }
        if (!passed) {
            throw new RuntimeException("Test Fail");
        }
        System.out.println("Test passed ");
    }
 
Example 21
@Test
public void joinGroupMulticastTest() throws Exception {
    InetAddress group = InetAddress.getByName("229.227.226.221");
    try (MulticastSocket s = new MulticastSocket(0)) {
        int port = s.getLocalPort();

        String addr = "localhost:" + port;
        AccessControlContext acc = getAccessControlContext(
                new SocketPermission(addr, "listen,resolve"),
                new SocketPermission("229.227.226.221", "connect,accept"));

        // Positive
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            s.joinGroup(group);
            s.leaveGroup(group);
            return null;
        }, acc);

        // Negative
        try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
                s.joinGroup(group);
                s.leaveGroup(group);
                fail("Expected SecurityException");
                return null;
            }, RESTRICTED_ACC);
        } catch (SecurityException expected) { }
    }

}
 
Example 22
Source Project: TencentKona-8   Source File: JdpTestCase.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() throws Exception {
    log.fine("Test started.");
    log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
            + ":" + String.valueOf(connection.port));
    log.fine(initialLogMessage());
    log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");

    startTime = System.currentTimeMillis();
    timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
    log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");

    MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);

    byte[] buffer = new byte[BUFFER_LENGTH];
    DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);

    do {
        try {
            socket.receive(datagram);
            onReceived(extractUDPpayload(datagram));
        } catch (SocketTimeoutException e) {
            onSocketTimeOut(e);
        }

        if (hasTestLivedLongEnough()) {
            shutdown();
        }

    } while (shouldContinue());
    log.fine("Test ended successfully.");
}
 
Example 23
public MulticastConnection(SocketInetAddress address, MessageSerializer<T> serializer) {
    this.address = address;
    this.serializer = serializer;
    try {
        socket = new MulticastSocket(address.getPort());
        socket.joinGroup(address.getAddress());
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
    localAddress = new SocketInetAddress(socket.getInetAddress(), socket.getLocalPort());
}
 
Example 24
public static void main(String[] args) throws Exception {

        boolean passed = true;
        try {
            MulticastSocket ms = new MulticastSocket();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface netIf = networkInterfaces.nextElement();
                if (isNetworkInterfaceTestable(netIf)) {
                    printNetIfDetails(netIf);
                    ms.setNetworkInterface(netIf);
                    NetworkInterface msNetIf = ms.getNetworkInterface();
                    if (netIf.equals(msNetIf)) {
                        System.out.println(" OK");
                    } else {
                        System.out.println("FAILED!!!");
                        printNetIfDetails(msNetIf);
                        passed = false;
                    }
                    System.out.println("------------------");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            passed = false;
        }
        if (!passed) {
            throw new RuntimeException("Test Fail");
        }
        System.out.println("Test passed ");
    }
 
Example 25
public static void main(String[] args) throws Exception {

        boolean passed = true;
        try {
            MulticastSocket ms = new MulticastSocket();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface netIf = networkInterfaces.nextElement();
                if (isNetworkInterfaceTestable(netIf)) {
                    printNetIfDetails(netIf);
                    ms.setNetworkInterface(netIf);
                    NetworkInterface msNetIf = ms.getNetworkInterface();
                    if (netIf.equals(msNetIf)) {
                        System.out.println(" OK");
                    } else {
                        System.out.println("FAILED!!!");
                        printNetIfDetails(msNetIf);
                        passed = false;
                    }
                    System.out.println("------------------");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            passed = false;
        }
        if (!passed) {
            throw new RuntimeException("Test Fail");
        }
        System.out.println("Test passed ");
    }
 
Example 26
Source Project: localization_nifi   Source File: MulticastUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(final MulticastSocket socket) {

        if (socket == null) {
            return;
        }

        try {
            socket.close();
        } catch (final Exception ex) {
            logger.debug("Failed to close multicast socket due to: " + ex, ex);
        }

    }
 
Example 27
Source Project: netty4.0.27Learn   Source File: OioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
private static MulticastSocket newSocket() {
    try {
        return new MulticastSocket(null);
    } catch (Exception e) {
        throw new ChannelException("failed to create a new socket", e);
    }
}
 
Example 28
Source Project: localization_nifi   Source File: MulticastListener.java    License: Apache License 2.0 5 votes vote down vote up
public void start() throws IOException {

        if (isRunning()) {
            return;
        }

        multicastSocket = MulticastUtils.createMulticastSocket(multicastAddress.getPort(), configuration);
        multicastSocket.joinGroup(multicastAddress.getAddress());

        executorService = Executors.newFixedThreadPool(numThreads);

        final ExecutorService runnableExecServiceRef = executorService;
        final MulticastSocket runnableMulticastSocketRef = multicastSocket;

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (runnableExecServiceRef.isShutdown() == false) {
                    try {
                        final byte[] buf = new byte[maxPacketSizeBytes];
                        final DatagramPacket packet = new DatagramPacket(buf, maxPacketSizeBytes);
                        runnableMulticastSocketRef.receive(packet);
                        runnableExecServiceRef.execute(new Runnable() {
                            @Override
                            public void run() {
                                dispatchRequest(multicastSocket, packet);
                            }
                        });
                    } catch (final SocketException | SocketTimeoutException ste) {
                        /* ignore so that we can accept connections in approximately a non-blocking fashion */
                    } catch (final Exception e) {
                        logger.warn("Cluster protocol receiver encountered exception: " + e, e);
                    }
                }
            }
        }).start();
    }
 
Example 29
Source Project: sailfish-core   Source File: MulticastSocketSession.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * Creates a new acceptor-side session instance.
    */
MulticastSocketSession(IoService service,
				MulticastSocket socket, IoProcessor<MulticastSocketSession> processor,
                       SocketAddress remoteAddress) 
   {
	super(service);
	
       this.service = service;
       this.socket = socket;
       this.config = new MulticastDatagramSessionConfig(socket);
       this.handler = service.getHandler();
       this.processor = processor;
       this.remoteAddress = (InetSocketAddress) remoteAddress;
       this.localAddress = (InetSocketAddress) socket.getLocalSocketAddress();
   }
 
Example 30
Source Project: openhab1-addons   Source File: SsdpDiscovery.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Broadcasts a SSDP discovery message into the network to find provided
 * services.
 * 
 * @return The Socket the answers will arrive at.
 * @throws UnknownHostException
 * @throws IOException
 * @throws SocketException
 * @throws UnsupportedEncodingException
 */
private MulticastSocket sendDiscoveryBroacast()
        throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
    InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
    final int port = 1900;
    MulticastSocket socket = new MulticastSocket(port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(130000);
    socket.joinGroup(multicastAddress);
    byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
            port);
    socket.send(datagramPacket);
    return socket;
}