Search in sources :

Example 96 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 = Product.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)

Example 97 with Selector

use of java.nio.channels.Selector in project spf4j by zolyfarkas.

the class TcpServerTest method testRejectingServer.

@Test(expected = IOException.class, timeout = 10000)
public void testRejectingServer() throws IOException, InterruptedException {
    String testSite = "localhost";
    ForkJoinPool pool = new ForkJoinPool(1024);
    try (TcpServer rejServer = new TcpServer(pool, new ClientHandler() {

        @Override
        public void handle(final Selector serverSelector, final SocketChannel clientChannel, final ExecutorService exec, final BlockingQueue<Runnable> tasksToRunBySelector, final UpdateablePriorityQueue<DeadlineAction> deadlineActions) throws IOException {
            clientChannel.configureBlocking(true);
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            // read something
            clientChannel.read(allocate);
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
            allocate.flip();
            clientChannel.write(allocate);
            clientChannel.close();
        }
    }, 1980, 10)) {
        rejServer.startAsync().awaitRunning();
        try (TcpServer server = new TcpServer(pool, new ProxyClientHandler(HostAndPort.fromParts(testSite, 1980), null, null, 10000, 5000), 1981, 10)) {
            server.startAsync().awaitRunning();
            byte[] readfromSite = readfromSite("http://localhost:1981");
            // probably wrong charset assumtion
            LOG.debug("Response: {}", new String(readfromSite, StandardCharsets.UTF_8));
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ClientHandler(org.spf4j.io.tcp.ClientHandler) ProxyClientHandler(org.spf4j.io.tcp.proxy.ProxyClientHandler) IOException(java.io.IOException) TcpServer(org.spf4j.io.tcp.TcpServer) ByteBuffer(java.nio.ByteBuffer) ProxyClientHandler(org.spf4j.io.tcp.proxy.ProxyClientHandler) DeadlineAction(org.spf4j.io.tcp.DeadlineAction) AbstractRunnable(org.spf4j.base.AbstractRunnable) ExecutorService(java.util.concurrent.ExecutorService) ForkJoinPool(java.util.concurrent.ForkJoinPool) Selector(java.nio.channels.Selector) Test(org.junit.Test)

Example 98 with Selector

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

the class NIOTest method testSelector.

@Test
public void testSelector() throws Exception {
    ServerSocket acceptor = new ServerSocket(0);
    Selector selector = Selector.open();
    // Create client server socket pair
    SocketChannel client = SocketChannel.open(acceptor.getLocalSocketAddress());
    Socket server = acceptor.accept();
    server.setTcpNoDelay(true);
    // Make the client non blocking and register it with selector for reads
    client.configureBlocking(false);
    SelectionKey key = client.register(selector, SelectionKey.OP_READ);
    // assert it is not selected
    assertTrue(key.isValid());
    assertFalse(key.isReadable());
    assertEquals(0, key.readyOps());
    // try selecting and assert nothing selected
    int selected = selector.selectNow();
    assertEquals(0, selected);
    assertEquals(0, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertFalse(key.isReadable());
    assertEquals(0, key.readyOps());
    // Write a byte from server to client
    server.getOutputStream().write(42);
    server.getOutputStream().flush();
    // select again and assert selection found for read
    selected = selector.select(1000);
    assertEquals(1, selected);
    assertEquals(1, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // select again and see that it is not reselect, but stays selected
    selected = selector.select(100);
    assertEquals(0, selected);
    assertEquals(1, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // read the byte
    ByteBuffer buf = ByteBuffer.allocate(1024);
    int len = client.read(buf);
    assertEquals(1, len);
    buf.flip();
    assertEquals(42, buf.get());
    buf.clear();
    // But this does not change the key
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // Even if we select again ?
    selected = selector.select(100);
    assertEquals(0, selected);
    assertEquals(1, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // Unless we remove the key from the select set
    // and then it is still flagged as isReadable()
    selector.selectedKeys().clear();
    assertEquals(0, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // Now if we select again - it is still flagged as readable!!!
    selected = selector.select(100);
    assertEquals(0, selected);
    assertEquals(0, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isReadable());
    assertEquals(1, key.readyOps());
    // Only when it is selected for something else does that state change.
    key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    selected = selector.select(1000);
    assertEquals(1, selected);
    assertEquals(1, selector.selectedKeys().size());
    assertTrue(key.isValid());
    assertTrue(key.isWritable());
    assertFalse(key.isReadable());
    assertEquals(SelectionKey.OP_WRITE, key.readyOps());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) ServerSocket(java.net.ServerSocket) ByteBuffer(java.nio.ByteBuffer) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Selector(java.nio.channels.Selector) Test(org.junit.Test)

Example 99 with Selector

use of java.nio.channels.Selector in project hazelcast by hazelcast.

the class SocketAcceptorThread method rebuildSelector.

private void rebuildSelector() throws IOException {
    selectorRecreateCount.inc();
    // cancel existing selection key, register new one on the new selector
    selectionKey.cancel();
    closeSelector();
    Selector newSelector = Selector.open();
    selector = newSelector;
    selectionKey = serverSocketChannel.register(newSelector, SelectionKey.OP_ACCEPT);
}
Also used : Selector(java.nio.channels.Selector)

Example 100 with Selector

use of java.nio.channels.Selector in project tomcat by apache.

the class NioChannel method getAttachment.

public Object getAttachment() {
    Poller pol = getPoller();
    Selector sel = pol != null ? pol.getSelector() : null;
    SelectionKey key = sel != null ? getIOChannel().keyFor(sel) : null;
    Object att = key != null ? key.attachment() : null;
    return att;
}
Also used : SelectionKey(java.nio.channels.SelectionKey) Poller(org.apache.tomcat.util.net.NioEndpoint.Poller) Selector(java.nio.channels.Selector)

Aggregations

Selector (java.nio.channels.Selector)189 SelectionKey (java.nio.channels.SelectionKey)85 IOException (java.io.IOException)71 SocketChannel (java.nio.channels.SocketChannel)52 InetSocketAddress (java.net.InetSocketAddress)38 ByteBuffer (java.nio.ByteBuffer)29 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 RemoteLaunchClient (io.aeron.test.launcher.RemoteLaunchClient)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 MethodSource (org.junit.jupiter.params.provider.MethodSource)6