Search in sources :

Example 46 with MulticastSocket

use of java.net.MulticastSocket in project jdk8u_jdk by JetBrains.

the class SocketPermissionTest method listenMulticastSocketTest.

@Test
public void listenMulticastSocketTest() throws Exception {
    // the hardcoded port number doesn't really matter since we expect the
    // security permission to be checked before the underlying operation.
    int port = 8899;
    String addr = "localhost:" + port;
    AccessControlContext acc = getAccessControlContext(new SocketPermission(addr, "listen"));
    // Positive
    AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
        try (MulticastSocket ms = new MulticastSocket(port)) {
        } catch (IOException intermittentlyExpected) {
        }
        return null;
    }, acc);
    // Negative
    try {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            try (MulticastSocket ms = new MulticastSocket(port)) {
            } catch (IOException intermittentlyExpected) {
            }
            fail("Expected SecurityException");
            return null;
        }, RESTRICTED_ACC);
    } catch (SecurityException expected) {
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) AccessControlContext(java.security.AccessControlContext) SocketPermission(java.net.SocketPermission) IOException(java.io.IOException) Test(org.testng.annotations.Test)

Example 47 with MulticastSocket

use of java.net.MulticastSocket in project chuidiang-ejemplos by chuidiang.

the class ClientRunnable method run.

public void run() {
    MulticastSocket multicastSocket = null;
    try {
        multicastSocket = new MulticastSocket(port);
        multicastSocket.joinGroup(group);
        while (true) {
            try {
                byte[] receiveData = new byte[256];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                multicastSocket.receive(receivePacket);
                byte[] data = Arrays.copyOf(receivePacket.getData(), receivePacket.getLength());
                LOGGER.info("Client received from : " + receivePacket.getAddress() + ", " + new String(data));
            } catch (Exception e) {
                LOGGER.error(null, e);
            }
        }
    } catch (Exception e) {
        LOGGER.error(null, e);
    } finally {
        multicastSocket.close();
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) DatagramPacket(java.net.DatagramPacket)

Example 48 with MulticastSocket

use of java.net.MulticastSocket in project ignite by apache.

the class TcpDiscoveryMulticastIpFinder method requestAddresses.

/**
 * Sends multicast address request message and waits for reply. Response wait time and number
 * of request attempts are configured as properties {@link #setResponseWaitTime} and
 * {@link #setAddressRequestAttempts}.
 *
 * @param mcastAddr Multicast address where to send request.
 * @param sockItf Optional interface multicast socket should be bound to.
 * @return Tuple where first value is collection of received addresses, second is boolean which is
 *      {@code true} if got error on send.
 */
private T2<Collection<InetSocketAddress>, Boolean> requestAddresses(InetAddress mcastAddr, @Nullable InetAddress sockItf) {
    Collection<InetSocketAddress> rmtAddrs = new HashSet<>();
    boolean sndErr = false;
    try {
        DatagramPacket reqPckt = new DatagramPacket(MSG_ADDR_REQ_DATA, MSG_ADDR_REQ_DATA.length, mcastAddr, mcastPort);
        byte[] resData = new byte[AddressResponse.MAX_DATA_LENGTH];
        DatagramPacket resPckt = new DatagramPacket(resData, resData.length);
        boolean sndError = false;
        for (int i = 0; i < addrReqAttempts; i++) {
            MulticastSocket sock = null;
            try {
                sock = new MulticastSocket(0);
                // Use 'false' to enable support for more than one node on the same machine.
                sock.setLoopbackMode(false);
                if (sockItf != null)
                    sock.setInterface(sockItf);
                sock.setSoTimeout(resWaitTime);
                if (ttl != -1)
                    sock.setTimeToLive(ttl);
                reqPckt.setData(MSG_ADDR_REQ_DATA);
                try {
                    sock.send(reqPckt);
                } catch (IOException e) {
                    sndErr = true;
                    if (!handleNetworkError(e))
                        break;
                    if (i < addrReqAttempts - 1) {
                        if (log.isDebugEnabled())
                            log.debug("Failed to send multicast address request (will retry in 500 ms): " + e);
                        U.sleep(500);
                    } else {
                        if (log.isDebugEnabled())
                            log.debug("Failed to send multicast address request: " + e);
                    }
                    sndError = true;
                    continue;
                }
                long rcvEnd = U.currentTimeMillis() + resWaitTime;
                try {
                    while (U.currentTimeMillis() < rcvEnd) {
                        // Try to receive multiple responses.
                        sock.receive(resPckt);
                        byte[] data = resPckt.getData();
                        if (!U.bytesEqual(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length)) {
                            U.error(log, "Failed to verify message header.");
                            continue;
                        }
                        AddressResponse addrRes;
                        try {
                            addrRes = new AddressResponse(data);
                        } catch (IgniteCheckedException e) {
                            LT.error(log, e, "Failed to deserialize multicast response.");
                            continue;
                        }
                        rmtAddrs.addAll(addrRes.addresses());
                    }
                } catch (SocketTimeoutException ignored) {
                    if (// DatagramSocket.receive timeout has expired.
                    log.isDebugEnabled())
                        log.debug("Address receive timeout.");
                }
            } catch (IOException e) {
                U.error(log, "Failed to request nodes addresses.", e);
            } finally {
                U.close(sock);
            }
            if (// Wait some time before re-sending address request.
            i < addrReqAttempts - 1)
                U.sleep(200);
        }
        if (log.isDebugEnabled())
            log.debug("Received nodes addresses: " + rmtAddrs);
        if (rmtAddrs.isEmpty() && sndError)
            U.quietAndWarn(log, "Failed to send multicast message (is multicast enabled on this node?).");
        return new T2<>(rmtAddrs, sndErr);
    } catch (IgniteInterruptedCheckedException ignored) {
        U.warn(log, "Got interrupted while sending address request.");
        Thread.currentThread().interrupt();
        return new T2<>(rmtAddrs, sndErr);
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SocketTimeoutException(java.net.SocketTimeoutException) DatagramPacket(java.net.DatagramPacket) T2(org.apache.ignite.internal.util.typedef.T2) HashSet(java.util.HashSet)

Example 49 with MulticastSocket

use of java.net.MulticastSocket in project cxf by apache.

the class UDPDestination method activate.

protected void activate() {
    WorkQueueManager queuem = bus.getExtension(WorkQueueManager.class);
    queue = queuem.getNamedWorkQueue("udp-transport");
    if (queue == null) {
        queue = queuem.getAutomaticWorkQueue();
    }
    try {
        URI uri = new URI(this.getAddress().getAddress().getValue());
        InetSocketAddress isa = null;
        if (StringUtils.isEmpty(uri.getHost())) {
            String s = uri.getSchemeSpecificPart();
            if (s.startsWith("//:")) {
                s = s.substring(3);
            }
            if (s.indexOf('/') != -1) {
                s = s.substring(0, s.indexOf('/'));
            }
            int port = Integer.parseInt(s);
            isa = new InetSocketAddress(port);
        } else {
            isa = new InetSocketAddress(uri.getHost(), uri.getPort());
        }
        if (isa.getAddress().isMulticastAddress()) {
            // ouch...
            MulticastSocket socket = new MulticastSocket(null);
            socket.setReuseAddress(true);
            socket.setReceiveBufferSize(64 * 1024);
            socket.setSendBufferSize(64 * 1024);
            socket.setTimeToLive(1);
            socket.setLoopbackMode(false);
            socket.bind(new InetSocketAddress(isa.getPort()));
            socket.setNetworkInterface(findNetworkInterface());
            socket.joinGroup(isa.getAddress());
            mcast = socket;
            queue.execute(new MCastListener());
        } else {
            acceptor = new NioDatagramAcceptor();
            acceptor.setHandler(new UDPIOHandler());
            acceptor.setDefaultLocalAddress(isa);
            DatagramSessionConfig dcfg = acceptor.getSessionConfig();
            dcfg.setReadBufferSize(64 * 1024);
            dcfg.setSendBufferSize(64 * 1024);
            dcfg.setReuseAddress(true);
            acceptor.bind();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) InetSocketAddress(java.net.InetSocketAddress) DatagramSessionConfig(org.apache.mina.transport.socket.DatagramSessionConfig) WorkQueueManager(org.apache.cxf.workqueue.WorkQueueManager) URI(java.net.URI) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) NioDatagramAcceptor(org.apache.mina.transport.socket.nio.NioDatagramAcceptor)

Example 50 with MulticastSocket

use of java.net.MulticastSocket in project cxf by apache.

the class WSDiscoveryClientTest method testMultiResponses.

@Test
public void testMultiResponses() throws Exception {
    // Disable the test on Redhat Enterprise Linux which doesn't enable the UDP broadcast by default
    if (System.getProperties().getProperty("os.name").equals("Linux") && System.getProperties().getProperty("os.version").indexOf("el") > 0) {
        System.out.println("Skipping MultiResponse test for REL");
        return;
    }
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int count = 0;
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        if (!networkInterface.isUp() || networkInterface.isLoopback()) {
            continue;
        }
        count++;
    }
    if (count == 0) {
        // no non-loopbacks, cannot do broadcasts
        System.out.println("Skipping MultiResponse test");
        return;
    }
    new Thread(new Runnable() {

        public void run() {
            try {
                // fake a discovery server to send back some canned messages.
                InetAddress address = InetAddress.getByName("239.255.255.250");
                MulticastSocket s = new MulticastSocket(Integer.parseInt(PORT));
                s.setBroadcast(true);
                s.setNetworkInterface(findIpv4Interface());
                s.setLoopbackMode(false);
                s.setReuseAddress(true);
                s.joinGroup(address);
                s.setReceiveBufferSize(64 * 1024);
                s.setSoTimeout(5000);
                byte[] bytes = new byte[64 * 1024];
                DatagramPacket p = new DatagramPacket(bytes, bytes.length, address, Integer.parseInt(PORT));
                s.receive(p);
                SocketAddress sa = p.getSocketAddress();
                String incoming = new String(p.getData(), 0, p.getLength(), StandardCharsets.UTF_8);
                int idx = incoming.indexOf("MessageID");
                idx = incoming.indexOf('>', idx);
                incoming = incoming.substring(idx + 1);
                idx = incoming.indexOf("</");
                incoming = incoming.substring(0, idx);
                for (int x = 1; x < 4; x++) {
                    InputStream ins = WSDiscoveryClientTest.class.getResourceAsStream("msg" + x + ".xml");
                    String msg = IOUtils.readStringFromStream(ins);
                    msg = msg.replace("urn:uuid:883d0d53-92aa-4066-9b6f-9eadb1832366", incoming);
                    byte[] out = msg.getBytes(StandardCharsets.UTF_8);
                    DatagramPacket outp = new DatagramPacket(out, 0, out.length, sa);
                    s.send(outp);
                }
                s.close();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }).start();
    Bus bus = BusFactory.newInstance().createBus();
    WSDiscoveryClient c = new WSDiscoveryClient(bus);
    c.setVersion10();
    c.setAddress("soap.udp://239.255.255.250:" + PORT);
    ProbeType pt = new ProbeType();
    ScopesType scopes = new ScopesType();
    pt.setScopes(scopes);
    ProbeMatchesType pmts = c.probe(pt, 1000);
    Assert.assertEquals(2, pmts.getProbeMatch().size());
    c.close();
    bus.shutdown(true);
}
Also used : ScopesType(org.apache.cxf.ws.discovery.wsdl.ScopesType) MulticastSocket(java.net.MulticastSocket) Bus(org.apache.cxf.Bus) ProbeType(org.apache.cxf.ws.discovery.wsdl.ProbeType) InputStream(java.io.InputStream) NetworkInterface(java.net.NetworkInterface) Endpoint(javax.xml.ws.Endpoint) DatagramPacket(java.net.DatagramPacket) ProbeMatchesType(org.apache.cxf.ws.discovery.wsdl.ProbeMatchesType) SocketAddress(java.net.SocketAddress) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Aggregations

MulticastSocket (java.net.MulticastSocket)50 IOException (java.io.IOException)19 DatagramPacket (java.net.DatagramPacket)19 InetSocketAddress (java.net.InetSocketAddress)16 InetAddress (java.net.InetAddress)15 Test (org.junit.Test)11 DatagramSocket (java.net.DatagramSocket)10 SocketException (java.net.SocketException)8 SocketTimeoutException (java.net.SocketTimeoutException)8 UnknownHostException (java.net.UnknownHostException)6 NetworkInterface (java.net.NetworkInterface)5 SocketAddress (java.net.SocketAddress)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 URI (java.net.URI)4 SubsetConfiguration (org.apache.commons.configuration2.SubsetConfiguration)4 ConfigBuilder (org.apache.hadoop.metrics2.impl.ConfigBuilder)4 ArrayList (java.util.ArrayList)3 Timer (java.util.Timer)3 ReentrantLock (java.util.concurrent.locks.ReentrantLock)3 BindException (java.net.BindException)2