java.net.MulticastSocket源码实例Demo

类java.net.MulticastSocket源码实例Demo

下面列出了java.net.MulticastSocket 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Tomcat8-Source-Read   文件: TesterMulticast.java
@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();
    }
}
 
源代码2 项目: commons-jcs   文件: UDPDiscoverySender.java
/**
 * 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;
}
 
源代码3 项目: cacheonix-core   文件: PlainMulticastSender.java
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;
            }
         }
      }
   }
 
源代码4 项目: openbd-core   文件: MultiCastManager.java
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() );
  }
}
 
源代码5 项目: DroidDLNA   文件: DatagramIOImpl.java
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);
        }
    }
 
源代码6 项目: qpid-jms   文件: MulticastDiscoveryAgent.java
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.");
        }
    }
}
 
源代码7 项目: fuchsia   文件: KNXnetIPRouter.java
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);
	}
}
 
源代码8 项目: dubbo-2.6.5   文件: MulticastRegistryTest.java
@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();
    }
}
 
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 ");
    }
 
源代码10 项目: nifi   文件: MulticastUtils.java
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);
        }

    }
 
源代码11 项目: dragonwell8_jdk   文件: JdpTestCase.java
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.");
}
 
源代码12 项目: netty-4.1.22   文件: OioDatagramChannel.java
private static MulticastSocket newSocket() {
    try {
        return new MulticastSocket(null);
    } catch (Exception e) {
        throw new ChannelException("failed to create a new socket", e);
    }
}
 
源代码13 项目: openhab1-addons   文件: SsdpDiscovery.java
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();
    }
}
 
源代码14 项目: cacheonix-core   文件: PlainMulticastSender.java
/**
 * 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()]);
}
 
@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;
}
 
源代码16 项目: gemfirexd-oss   文件: UDP.java
/**
 *
 * @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;
        }
    }
}
 
@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;
}
 
@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;
}
 
@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;
}
 
源代码20 项目: TencentKona-8   文件: SetGetNetworkInterfaceTest.java
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 ");
    }
 
源代码21 项目: TencentKona-8   文件: SocketPermissionTest.java
@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) { }
    }

}
 
源代码22 项目: TencentKona-8   文件: JdpTestCase.java
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.");
}
 
源代码23 项目: pushfish-android   文件: MulticastConnection.java
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());
}
 
源代码24 项目: jdk8u60   文件: SetGetNetworkInterfaceTest.java
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 ");
    }
 
源代码25 项目: jdk8u-dev-jdk   文件: SetGetNetworkInterfaceTest.java
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 ");
    }
 
源代码26 项目: localization_nifi   文件: MulticastUtils.java
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);
        }

    }
 
源代码27 项目: netty4.0.27Learn   文件: OioDatagramChannel.java
private static MulticastSocket newSocket() {
    try {
        return new MulticastSocket(null);
    } catch (Exception e) {
        throw new ChannelException("failed to create a new socket", e);
    }
}
 
源代码28 项目: localization_nifi   文件: MulticastListener.java
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();
    }
 
源代码29 项目: sailfish-core   文件: MulticastSocketSession.java
/**
    * 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();
   }
 
源代码30 项目: openhab1-addons   文件: SsdpDiscovery.java
/**
 * 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;
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 同包方法