Search in sources :

Example 31 with Selector

use of java.nio.channels.Selector in project jdk8u_jdk by JetBrains.

the class WakeupAfterClose method main.

public static void main(String[] args) throws Exception {
    final Selector sel = Selector.open();
    Runnable r = new Runnable() {

        public void run() {
            try {
                sel.select();
            } catch (IOException x) {
                x.printStackTrace();
            }
        }
    };
    // start thread to block in Selector
    Thread t = new Thread(r);
    t.start();
    // give thread time to start
    Thread.sleep(1000);
    // interrupt, close, and wakeup is the magic sequence to provoke the NPE
    t.interrupt();
    sel.close();
    sel.wakeup();
}
Also used : IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 32 with Selector

use of java.nio.channels.Selector in project baseio by generallycloud.

the class SocketSelectorEventLoop method openSelector.

@SuppressWarnings("rawtypes")
private SocketSelector openSelector(SelectableChannel channel) throws IOException {
    SelectorProvider provider = SelectorProvider.provider();
    Object res = AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            try {
                return Class.forName("sun.nio.ch.SelectorImpl");
            } catch (Throwable cause) {
                return cause;
            }
        }
    });
    final Selector selector = provider.openSelector();
    if (res instanceof Throwable) {
        return new NioSocketSelector(this, channel, selector);
    }
    final Class selectorImplClass = (Class) res;
    final SelectionKeySet keySet = new SelectionKeySet();
    res = AccessController.doPrivileged(new PrivilegedAction<Object>() {

        @Override
        public Object run() {
            try {
                Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
                Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");
                Throwable cause = ClassUtil.trySetAccessible(selectedKeysField);
                if (cause != null) {
                    return cause;
                }
                cause = ClassUtil.trySetAccessible(publicSelectedKeysField);
                if (cause != null) {
                    return cause;
                }
                selectedKeysField.set(selector, keySet);
                publicSelectedKeysField.set(selector, keySet);
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    });
    if (res instanceof Throwable) {
        return new NioSocketSelector(this, channel, selector);
    }
    selectionKeySet = keySet;
    return new SelectionKeyNioSocketSelector(this, channel, selector, keySet);
}
Also used : SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) Field(java.lang.reflect.Field) SelectorProvider(java.nio.channels.spi.SelectorProvider) PrivilegedAction(java.security.PrivilegedAction) Selector(java.nio.channels.Selector)

Example 33 with Selector

use of java.nio.channels.Selector in project aeron by real-logic.

the class SendHackSelectReceiveUdpPing method run.

private void run() throws IOException {
    receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    receiveChannel.register(selector, OP_READ, this);
    final NioSelectedKeySet keySet = Common.keySet(selector);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(HISTOGRAM, SEND_ADDRESS, buffer, sendChannel, selector, keySet, running);
        HISTOGRAM.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioSelectedKeySet(org.agrona.nio.NioSelectedKeySet) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) Selector(java.nio.channels.Selector)

Example 34 with Selector

use of java.nio.channels.Selector in project aeron by real-logic.

the class SendSelectReceiveUdpPing method run.

private void run() throws IOException {
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final IntSupplier handler = () -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long timestamp = buffer.getLong(SIZE_OF_LONG);
            if (receivedSequenceNumber != sequenceNumber) {
                throw new IllegalStateException("Data Loss:" + sequenceNumber + " to " + receivedSequenceNumber);
            }
            final long duration = System.nanoTime() - timestamp;
            histogram.recordValue(duration);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, handler);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, SEND_ADDRESS, buffer, sendChannel, selector, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Histogram(org.HdrHistogram.Histogram) IntSupplier(java.util.function.IntSupplier) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 35 with Selector

use of java.nio.channels.Selector in project smarthome by eclipse.

the class LifxLightDiscovery method handlePacket.

private void handlePacket(Packet packet, InetSocketAddress address) {
    logger.trace("Discovery : Packet type '{}' received from '{}' for '{}' with sequence '{}' and source '{}'", new Object[] { packet.getClass().getSimpleName(), address.toString(), packet.getTarget().getHex(), packet.getSequence(), Long.toString(packet.getSource(), 16) });
    if (packet.getSource() == sourceId || packet.getSource() == 0) {
        MACAddress macAddress = packet.getTarget();
        DiscoveredLight light = discoveredLights.get(macAddress);
        if (packet instanceof StateServiceResponse) {
            int port = (int) ((StateServiceResponse) packet).getPort();
            if (port != 0) {
                try {
                    InetSocketAddress socketAddress = new InetSocketAddress(address.getAddress(), port);
                    if (light == null || (!socketAddress.equals(light.socketAddress))) {
                        if (light != null) {
                            light.cancelUnicastKey();
                        }
                        Selector lightSelector = selector;
                        if (lightSelector != null) {
                            String logId = getLogId(macAddress, socketAddress);
                            light = new DiscoveredLight(lightSelector, macAddress, socketAddress, logId, openUnicastChannel(lightSelector, logId, socketAddress));
                            discoveredLights.put(macAddress, light);
                        }
                    }
                } catch (Exception e) {
                    logger.warn("{} while connecting to IP address: {}", e.getClass().getSimpleName(), e.getMessage());
                    return;
                }
            }
        } else if (light != null) {
            if (packet instanceof StateLabelResponse) {
                light.label = ((StateLabelResponse) packet).getLabel().trim();
            } else if (packet instanceof StateVersionResponse) {
                try {
                    light.product = Products.getProductFromProductID(((StateVersionResponse) packet).getProduct());
                    light.productVersion = ((StateVersionResponse) packet).getVersion();
                } catch (IllegalArgumentException e) {
                    logger.debug("Discovered an unsupported light ({}): {}", light.macAddress.getAsLabel(), e.getMessage());
                    light.supportedProduct = false;
                }
            }
        }
        if (light != null && light.isDataComplete()) {
            try {
                thingDiscovered(createDiscoveryResult(light));
            } catch (IllegalArgumentException e) {
                logger.trace("{} while creating discovery result of light ({})", e.getClass().getSimpleName(), light.logId, e);
            }
        }
    }
}
Also used : MACAddress(org.eclipse.smarthome.binding.lifx.internal.fields.MACAddress) InetSocketAddress(java.net.InetSocketAddress) StateLabelResponse(org.eclipse.smarthome.binding.lifx.internal.protocol.StateLabelResponse) StateServiceResponse(org.eclipse.smarthome.binding.lifx.internal.protocol.StateServiceResponse) StateVersionResponse(org.eclipse.smarthome.binding.lifx.internal.protocol.StateVersionResponse) Selector(java.nio.channels.Selector)

Aggregations

Selector (java.nio.channels.Selector)186 SelectionKey (java.nio.channels.SelectionKey)84 IOException (java.io.IOException)70 SocketChannel (java.nio.channels.SocketChannel)51 InetSocketAddress (java.net.InetSocketAddress)38 ByteBuffer (java.nio.ByteBuffer)28 ServerSocketChannel (java.nio.channels.ServerSocketChannel)27 Test (org.junit.Test)14 DatagramChannel (java.nio.channels.DatagramChannel)13 ClosedChannelException (java.nio.channels.ClosedChannelException)12 CancelledKeyException (java.nio.channels.CancelledKeyException)11 NioEndpoint (org.apache.tomcat.util.net.NioEndpoint)10 ClosedSelectorException (java.nio.channels.ClosedSelectorException)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 EOFException (java.io.EOFException)7 ServerSocket (java.net.ServerSocket)7 SelectableChannel (java.nio.channels.SelectableChannel)7 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)5 Iterator (java.util.Iterator)5 MemberImpl (org.apache.catalina.tribes.membership.MemberImpl)5