use of java.net.MulticastSocket in project wildfly by wildfly.
the class ManagedSocketFactoryTest method createMulticastSocket.
@Test
public void createMulticastSocket() throws IOException {
MulticastSocket socket1 = mock(MulticastSocket.class);
MulticastSocket socket2 = mock(MulticastSocket.class);
MulticastSocket socket3 = mock(MulticastSocket.class);
MulticastSocket socket4 = mock(MulticastSocket.class);
SocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 1);
when(this.manager.createMulticastSocket("test", new InetSocketAddress(0))).thenReturn(socket1);
when(this.manager.createMulticastSocket("test", new InetSocketAddress(1))).thenReturn(socket2);
when(this.manager.createMulticastSocket("test", address)).thenReturn(socket3);
when(this.manager.createMulticastSocket("test")).thenReturn(socket4);
MulticastSocket result1 = this.subject.createMulticastSocket("test");
MulticastSocket result2 = this.subject.createMulticastSocket("test", 1);
MulticastSocket result3 = this.subject.createMulticastSocket("test", address);
MulticastSocket result4 = this.subject.createMulticastSocket("test", null);
assertSame(socket1, result1);
assertSame(socket2, result2);
assertSame(socket3, result3);
assertSame(socket4, result4);
}
use of java.net.MulticastSocket in project tomee by apache.
the class MulticastTool method main.
public static void main(final String[] array) throws Exception {
final CommandParser.Arguments arguments;
try {
arguments = cmd.parse(array);
} catch (CommandParser.HelpException e) {
System.exit(0);
// never reached, but keeps compiler happy
throw new Exception();
} catch (CommandParser.InvalidOptionsException e) {
System.exit(1);
// never reached, but keeps compiler happy
throw new Exception();
}
final Options options = arguments.options();
final SimpleDateFormat format = new SimpleDateFormat(options.get("date-format", "HH:mm:ss"));
final String host = options.get("host", "239.255.3.2");
final int port = options.get("port", 6142);
final InetAddress inetAddress = InetAddress.getByName(host);
final InetSocketAddress address = new InetSocketAddress(inetAddress, port);
final MulticastSocket multicast = new MulticastSocket(port);
multicast.joinGroup(inetAddress);
if (options.has("reuse-address")) {
multicast.setReuseAddress(options.get("reuse-address", false));
}
if (options.has("broadcast")) {
multicast.setBroadcast(options.get("broadcast", false));
}
if (options.has("loopback-mode")) {
multicast.setLoopbackMode(options.get("loopback-mode", false));
}
if (options.has("send-buffer-size")) {
multicast.setSendBufferSize(options.get("send-buffer-size", 0));
}
if (options.has("receive-buffer-size")) {
multicast.setReceiveBufferSize(options.get("receive-buffer-size", 0));
}
if (options.has("so-timeout")) {
multicast.setSoTimeout(options.get("so-timeout", 0));
}
if (options.has("time-to-live")) {
multicast.setTimeToLive(options.get("time-to-live", 0));
}
if (options.has("traffic-class")) {
multicast.setTrafficClass(options.get("traffic-class", 0));
}
System.out.println("Connected");
print("host", host);
print("port", port);
System.out.println();
System.out.println("Socket");
print("broadcast", multicast.getBroadcast());
print("loopback-mode", multicast.getLoopbackMode());
print("receive-buffer-size", multicast.getReceiveBufferSize());
print("reuse-address", multicast.getReuseAddress());
print("send-buffer-size", multicast.getSendBufferSize());
print("so-timeout", multicast.getSoTimeout());
print("time-to-live", multicast.getTimeToLive());
print("traffic-class", multicast.getTrafficClass());
System.out.println();
if (options.has("send")) {
final String send = options.get("send", "");
final long rate = options.get("rate", 1000);
System.out.println("Sending");
print("send", send);
print("rate", rate);
System.out.println();
final Send message = new Send(address, multicast, send);
if (rate > 0) {
final Timer timer = new Timer("Multicast Send", true);
timer.scheduleAtFixedRate(message, 0, rate);
} else {
message.run();
message.close();
}
}
System.out.println("Listening....");
final byte[] buf = new byte[BUFF_SIZE];
final DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
//noinspection InfiniteLoopStatement
while (true) {
try {
multicast.receive(packet);
if (packet.getLength() > 0) {
final StringBuilder sb = new StringBuilder();
sb.append(format.format(new Date()));
sb.append(" - ");
sb.append(packet.getAddress().getHostAddress());
sb.append(" - ");
final String str = new String(packet.getData(), packet.getOffset(), packet.getLength());
sb.append(str);
System.out.println(sb.toString());
}
} catch (SocketTimeoutException e) {
final StringBuilder sb = new StringBuilder();
sb.append(format.format(new Date()));
sb.append(" - ");
sb.append("ERROR");
sb.append(" - ");
sb.append(e.getMessage());
System.out.println(sb.toString());
}
}
}
use of java.net.MulticastSocket in project tomee by apache.
the class MulticastPulseClient method getSockets.
public static MulticastSocket[] getSockets(final InetAddress ia, final int port) throws Exception {
final ArrayList<MulticastSocket> list = new ArrayList<MulticastSocket>();
for (final NetworkInterface ni : getInterfaces()) {
MulticastSocket ms = null;
try {
ms = new MulticastSocket(port);
ms.setNetworkInterface(ni);
ms.setSoTimeout(0);
ms.setTimeToLive(TTL);
if (!ms.getBroadcast()) {
ms.setBroadcast(true);
}
ms.joinGroup(ia);
list.add(ms);
} catch (Exception e) {
if (null != ms) {
try {
ms.close();
} catch (Exception t) {
//Ignore
}
}
}
}
return list.toArray(new MulticastSocket[list.size()]);
}
use of java.net.MulticastSocket in project tomee by apache.
the class MulticastPulseAgentTest method testBroadcastBadUri.
@Test
public void testBroadcastBadUri() throws Exception {
if ("true".equals(System.getProperty("skipMulticastTests"))) {
Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
return;
}
final DiscoveryListener original = agent.getDiscoveryListener();
final CountDownLatch latch = new CountDownLatch(1);
final DiscoveryListener listener = new DiscoveryListener() {
@Override
public void serviceAdded(final URI service) {
latch.countDown();
System.out.println("added = " + service);
}
@Override
public void serviceRemoved(final URI service) {
latch.countDown();
System.out.println("removed = " + service);
}
};
agent.setDiscoveryListener(listener);
final String[] hosts = agent.getHosts().split(",");
final String host = hosts[hosts.length - 1];
boolean removed = agent.removeFromIgnore(host);
org.junit.Assert.assertTrue("Host is already ignored", !removed);
final Future<?> future = executor.submit(new Runnable() {
@Override
public void run() {
try {
final InetAddress ia = getAddress(MulticastPulseAgentTest.host);
final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup + MulticastPulseAgent.BADURI + host).getBytes(Charset.forName("UTF-8"));
final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
final MulticastSocket[] multicastSockets = MulticastPulseAgent.getSockets(MulticastPulseAgentTest.host, port);
for (int i = 0; i < 5; i++) {
for (final MulticastSocket socket : multicastSockets) {
try {
socket.send(request);
Thread.sleep(100);
} catch (final Exception e) {
System.out.println("Failed to broadcast bad URI on: " + socket.getInterface().getHostAddress());
e.printStackTrace();
}
}
}
} catch (final Exception e) {
System.out.println("Failed to broadcast bad URI");
e.printStackTrace();
}
}
});
final boolean await = latch.await(20, TimeUnit.SECONDS);
removed = agent.removeFromIgnore(host);
agent.setDiscoveryListener(original);
org.junit.Assert.assertTrue("Failed to remove host", removed);
org.junit.Assert.assertTrue("Failed to unlatch", await);
}
use of java.net.MulticastSocket in project tomee by apache.
the class MulticastPulseAgentTest method test.
/**
* Most of this code is identical to org.apache.openejb.client.MulticastPulseClient#discoverURIs
* <p/>
* The MulticastPulseClient class is not shared or available here so the test has to emulate it.
*
* @throws Exception On error
*/
@Test
public void test() throws Exception {
if ("true".equals(System.getProperty("skipMulticastTests"))) {
Logger.getLogger(this.getClass().getName()).warning("Skipping MulticastTest " + this.getClass().getName());
return;
}
final InetAddress ia;
try {
ia = InetAddress.getByName(host);
} catch (final UnknownHostException e) {
throw new Exception(host + " is not a valid address", e);
}
if (null == ia || !ia.isMulticastAddress()) {
throw new Exception(host + " is not a valid multicast address");
}
//Returns at least one socket per valid network interface
final MulticastSocket[] clientSockets = MulticastPulseAgent.getSockets(host, port);
//No point going on if we don't have sockets...
if (clientSockets.length < 1) {
System.out.println("Cannnot perform multipulse test without a valid interface");
return;
}
final byte[] bytes = (MulticastPulseAgent.CLIENT + forGroup).getBytes(utf8);
final DatagramPacket request = new DatagramPacket(bytes, bytes.length, new InetSocketAddress(ia, port));
final AtomicBoolean running = new AtomicBoolean(true);
final Timer timer = new Timer(true);
final Set<URI> set = new TreeSet<URI>(new Comparator<URI>() {
@Override
public int compare(final URI uri1, final URI uri2) {
//Ignore server hostname
URI u1 = URI.create(uri1.getSchemeSpecificPart());
URI u2 = URI.create(uri2.getSchemeSpecificPart());
//Ignore scheme (ejb,ejbs,etc.)
u1 = URI.create(u1.getSchemeSpecificPart());
u2 = URI.create(u2.getSchemeSpecificPart());
//Compare URI hosts
int i = compare(u1.getHost(), u2.getHost());
if (i != 0) {
i = uri1.compareTo(uri2);
}
return i;
}
private boolean isIPv4LiteralAddress(final InetAddress val) {
return Inet4Address.class.isInstance(val);
}
private boolean isIPv6LiteralAddress(final InetAddress val) {
return Inet6Address.class.isInstance(val);
}
private int compare(final String h1, final String h2) {
try {
InetAddress address1 = null;
InetAddress address2 = null;
try {
address1 = InetAddress.getByName(h1);
address2 = InetAddress.getByName(h2);
} catch (final UnknownHostException e) {
// no-op
}
if (isIPv4LiteralAddress(address1)) {
if (isIPv6LiteralAddress(address2)) {
return -1;
}
} else if (isIPv6LiteralAddress(address1)) {
if (isIPv4LiteralAddress(address2)) {
return 1;
}
} else if (0 != h1.compareTo(h2)) {
return -1;
}
} catch (final Throwable e) {
//Ignore
}
return h1.compareTo(h2);
}
});
final ReentrantLock setLock = new ReentrantLock();
//Start threads that listen for multicast packets on our channel.
//These need to start 'before' we pulse a request.
final ArrayList<Future> futures = new ArrayList<Future>();
final CountDownLatch latch = new CountDownLatch(clientSockets.length);
for (final MulticastSocket socket : clientSockets) {
futures.add(executor.submit(new Runnable() {
@Override
public void run() {
String name = "Unknown interface";
try {
name = socket.getNetworkInterface().getDisplayName();
} catch (final Throwable e) {
//Ignore
}
System.out.println("Entered MulticastPulse client thread on: " + name);
final DatagramPacket response = new DatagramPacket(new byte[2048], 2048);
latch.countDown();
while (running.get()) {
try {
socket.receive(response);
final SocketAddress sa = response.getSocketAddress();
if ((sa instanceof InetSocketAddress)) {
int len = response.getLength();
if (len > 2048) {
len = 2048;
}
String s = new String(response.getData(), 0, len);
if (s.startsWith(MulticastPulseAgent.SERVER)) {
s = (s.replace(MulticastPulseAgent.SERVER, ""));
final String group = s.substring(0, s.indexOf(':'));
s = s.substring(group.length() + 1);
if (!"*".equals(forGroup) && !forGroup.equals(group)) {
continue;
}
final String services = s.substring(0, s.lastIndexOf('|'));
s = s.substring(services.length() + 1);
final String[] serviceList = services.split("\\|");
final String[] hosts = s.split(",");
System.out.println(String.format("\n" + name + " received Server pulse:\n\tGroup: %1$s\n\tServices: %2$s\n\tServer: %3$s\n", group, services, s));
for (final String svc : serviceList) {
if (MulticastPulseAgent.EMPTY.equals(svc)) {
continue;
}
final URI serviceUri;
try {
serviceUri = URI.create(svc);
} catch (final Throwable e) {
continue;
}
if (schemes.contains(serviceUri.getScheme())) {
//Just because multicast was received on this host is does not mean the service is on the same
//We can however use this to identify an individual machine and group
final String serverHost = ((InetSocketAddress) response.getSocketAddress()).getAddress().getHostAddress();
final String serviceHost = serviceUri.getHost();
if (MulticastPulseAgent.isLocalAddress(serviceHost, false)) {
if (!MulticastPulseAgent.isLocalAddress(serverHost, false)) {
//A local service is only available to a local client
continue;
}
}
final String fullsvc = ("mp-" + serverHost + ":" + group + ":" + svc);
setLock.lock();
try {
if (fullsvc.contains("0.0.0.0")) {
for (final String h : hosts) {
if (!h.replace("[", "").startsWith("2001:0:")) {
//Filter Teredo
set.add(URI.create(fullsvc.replace("0.0.0.0", ipFormat(h))));
}
}
} else if (fullsvc.contains("[::]")) {
for (final String h : hosts) {
if (!h.replace("[", "").startsWith("2001:0:")) {
//Filter Teredo
set.add(URI.create(fullsvc.replace("[::]", ipFormat(h))));
}
}
} else {
//Just add as is
set.add(URI.create(fullsvc));
}
} catch (final Throwable e) {
//Ignore
} finally {
setLock.unlock();
}
} else {
System.out.println("Reject service: " + serviceUri.toASCIIString() + " - Not looking for scheme: " + serviceUri.getScheme());
}
}
}
}
} catch (final Throwable e) {
//Ignore
}
}
System.out.println("Exit MulticastPulse client thread on: " + name);
System.out.flush();
}
}));
}
//Allow slow thread starts
System.out.println("Wait for threads to start");
int timeout = 5000;
try {
//Give threads a generous amount of time to start
if (latch.await(15, TimeUnit.SECONDS)) {
System.out.println("Threads have started");
//Pulse the server - It is thread safe to use same sockets as send/receive synchronization is only on the packet
for (final MulticastSocket socket : clientSockets) {
try {
socket.send(request);
} catch (final Throwable e) {
//Ignore
}
}
} else {
timeout = 1;
System.out.println("Giving up on threads");
}
} catch (final InterruptedException e) {
timeout = 1;
}
//Kill the threads after timeout
timer.schedule(new TimerTask() {
@Override
public void run() {
running.set(false);
for (final Future future : futures) {
try {
future.cancel(true);
} catch (final Throwable e) {
//Ignore
}
}
for (final MulticastSocket socket : clientSockets) {
try {
socket.leaveGroup(ia);
} catch (final Throwable e) {
//Ignore
}
try {
socket.close();
} catch (final Throwable e) {
//Ignore
}
}
}
}, timeout);
//Wait for threads to complete
for (final Future future : futures) {
try {
future.get();
} catch (final Throwable e) {
//Ignore
}
}
System.out.println();
System.out.flush();
final ArrayList<String> list = new ArrayList<String>();
final TreeSet<URI> uris = new TreeSet<URI>(set);
for (final URI uri : uris) {
final String astr = uri.toASCIIString();
System.out.println("MultiPulse discovered: " + astr);
if (list.contains(astr)) {
System.out.println("Duplicate uri: " + uri);
}
org.junit.Assert.assertTrue(!list.contains(astr));
list.add(astr);
}
System.out.println("Multipulse complete");
//If timeout == 1 assume either a cancel or the test took too long (Will not fail)
org.junit.Assert.assertTrue(timeout == 1 || set.size() > 0);
}
Aggregations