Search in sources :

Example 41 with MulticastSocket

use of java.net.MulticastSocket in project intellij-plugins by JetBrains.

the class MulticastPingThread method run.

@Override
public void run() {
    LOG.info(getName() + ": Start thread.");
    Runtime.getRuntime().addShutdownHook(new Thread("IDETalk shutdown hook") {

        @Override
        public void run() {
            // Yes, MulticastPingThread is daemon, but it still keeps JVM running.
            MulticastPingThread.this.interrupt();
        // Seems this is some troubles with native calls.
        // see IDEA-52501
        }
    });
    myDatagramSocket = null;
    myIsRunning = true;
    try {
        myDatagramSocket = new MulticastSocket(MULTICAST_PORT);
        myDatagramSocket.setInterface(mySelfAddress);
        myDatagramSocket.joinGroup(InetAddress.getByName(MULTICAST_ADORES));
        byte[] buffer = new byte[BUFFER_SIZE];
        while (myIsRunning) {
            try {
                DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
                LOG.debug(getName() + ": Listening for multicast messages... ");
                myStarted = true;
                myDatagramSocket.receive(datagramPacket);
                String message = new String(buffer, 0, datagramPacket.getLength());
                final InetAddress remoteAddress = datagramPacket.getAddress();
                if (LOG.isDebugEnabled()) {
                    LOG.debug(getName() + ": Got multicast message '" + message + "' from " + remoteAddress);
                }
                if (message.startsWith(PING_MESSAGE)) {
                    final int targetPort = extractPort(message);
                    if (shouldAddSelf(datagramPacket, targetPort)) {
                        addSelfInfoTo(remoteAddress, targetPort);
                    }
                }
            } catch (SocketException e) {
                if (!"Socket closed".equalsIgnoreCase(e.getMessage())) {
                    LOG.error(e.getMessage(), e);
                } else {
                    myIsRunning = false;
                }
            }
        }
    } catch (SocketException e) {
        final String msg = e.getMessage();
        if (msg != null) {
            LOG.info(msg, e);
        } else {
            logError(e);
        }
    } catch (IOException e) {
        logError(e);
    } finally {
        myIsRunning = false;
        if (myDatagramSocket != null && !myDatagramSocket.isClosed()) {
            myDatagramSocket.close();
        }
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) SocketException(java.net.SocketException) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 42 with MulticastSocket

use of java.net.MulticastSocket in project intellij-plugins by JetBrains.

the class MulticastPingThread method sendMulticastPingRequest.

public void sendMulticastPingRequest() throws IOException {
    if (!myIsRunning)
        return;
    MulticastSocket datagramSocket = null;
    try {
        datagramSocket = new MulticastSocket();
        datagramSocket.setInterface(mySelfAddress);
        LOG.debug("Sending Multicast ping request: " + mySelfAddress);
        sendMessage(datagramSocket, PING_MESSAGE + myUserMonitorClient.getPort());
        myFailuresCounter = 0;
    } catch (IOException e) {
        if (++myFailuresCounter > ALLOWED_FAILURES) {
            LOG.info("Unable to send multicast request on interface " + mySelfAddress + ". I give up after " + myFailuresCounter + " attempts.", e);
            myIsRunning = false;
        }
    } finally {
        if (datagramSocket != null) {
            datagramSocket.close();
        }
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) IOException(java.io.IOException)

Example 43 with MulticastSocket

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

the class Reuse method main.

public static void main(String[] args) throws Exception {
    MulticastSocket s1, s2;
    try {
        s1 = new MulticastSocket(4160);
        s2 = new MulticastSocket(4160);
        s1.close();
        s2.close();
    } catch (BindException e) {
        throw new RuntimeException("MulticastSocket do no set SO_REUSEADDR");
    }
}
Also used : MulticastSocket(java.net.MulticastSocket) BindException(java.net.BindException)

Example 44 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 45 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)

Aggregations

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