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();
}
}
}
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();
}
}
}
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");
}
}
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) {
}
}
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);
}
}
Aggregations