Search in sources :

Example 36 with Selector

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

the class LifxLightCommunicationHandler method start.

public void start() {
    try {
        lock.lock();
        logger.debug("{} : Starting communication handler", logId);
        logger.debug("{} : Using '{}' as source identifier", logId, Long.toString(sourceId, 16));
        ScheduledFuture<?> localNetworkJob = networkJob;
        if (localNetworkJob == null || localNetworkJob.isCancelled()) {
            networkJob = scheduler.scheduleWithFixedDelay(this::receiveAndHandlePackets, 0, PACKET_INTERVAL, TimeUnit.MILLISECONDS);
        }
        currentLightState.setOffline();
        Selector localSelector = Selector.open();
        selector = localSelector;
        if (isBroadcastEnabled()) {
            broadcastKey = openBroadcastChannel(selector, logId, broadcastPort);
            selectorContext = new LifxSelectorContext(localSelector, sourceId, sequenceNumberSupplier, logId, host, macAddress, broadcastKey, unicastKey);
            broadcastPacket(new GetServiceRequest());
        } else {
            unicastKey = openUnicastChannel(selector, logId, host);
            selectorContext = new LifxSelectorContext(localSelector, sourceId, sequenceNumberSupplier, logId, host, macAddress, broadcastKey, unicastKey);
            sendPacket(new GetServiceRequest());
        }
    } catch (IOException e) {
        logger.error("{} while starting LIFX communication handler for light '{}' : {}", e.getClass().getSimpleName(), logId, e.getMessage(), e);
    } finally {
        lock.unlock();
    }
}
Also used : GetServiceRequest(org.eclipse.smarthome.binding.lifx.internal.protocol.GetServiceRequest) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 37 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 38 with Selector

use of java.nio.channels.Selector in project iobserve-analysis by research-iobserve.

the class MultipleConnectionTcpReaderStage method execute.

@Override
protected void execute() {
    try {
        final ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.bind(new InetSocketAddress(this.inputPort));
        serverSocket.configureBlocking(false);
        final Selector readSelector = Selector.open();
        while (this.isActive()) {
            final SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel != null) {
                this.logger.debug("Connection from {}.", socketChannel.getRemoteAddress().toString());
                // add socketChannel to list of channels
                socketChannel.configureBlocking(false);
                final SelectionKey key = socketChannel.register(readSelector, SelectionKey.OP_READ);
                final Connection connection = new Connection(socketChannel, this.bufferSize);
                key.attach(connection);
            }
            final int readReady = readSelector.selectNow();
            if (readReady > 0) {
                final Set<SelectionKey> selectedKeys = readSelector.selectedKeys();
                final Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                while (keyIterator.hasNext()) {
                    final SelectionKey key = keyIterator.next();
                    this.readFromSocket(key);
                    keyIterator.remove();
                }
                selectedKeys.clear();
            }
        }
    } catch (final ClosedByInterruptException e) {
        this.logger.info("External shutdown called");
    } catch (final IOException e) {
        this.logger.error("Cannot establish listening port", e);
    } finally {
        this.workCompleted();
    }
}
Also used : ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 39 with Selector

use of java.nio.channels.Selector in project GIPC by pdewan.

the class NioServer method initSelector.

private Selector initSelector() throws IOException {
    // Create a new selector
    Selector socketSelector = SelectorProvider.provider().openSelector();
    // Create a new non-blocking server socket channel
    this.serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    // Bind the server socket to the specified address and port
    InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
    serverChannel.socket().bind(isa);
    // Register the server socket channel, indicating an interest in
    // accepting new connections
    serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
    return socketSelector;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Selector(java.nio.channels.Selector)

Example 40 with Selector

use of java.nio.channels.Selector in project GIPC by pdewan.

the class NioClientExp method syncWrite.

private void syncWrite(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    int ops = key.interestOps();
    key.cancel();
    // socketChannel.register(null, 0);
    SelectableChannel retChannel = socketChannel.configureBlocking(true);
    OutputStream socketOutputStream = socketChannel.socket().getOutputStream();
    // synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    // Write until there's not more data ...
    while (!queue.isEmpty()) {
        ByteBuffer buf = (ByteBuffer) queue.get(0);
        // socketChannel.write(buf);
        // OutputStream socketOutputStream = socketChannel.socket().getOutputStream();
        socketOutputStream.write(buf.array());
        // socketChannel.register(this.selector, ChangeRequest.CHANGEOPS);
        // this seems to fil up
        // if (buf.remaining() > 0) {
        // // ... or the socket's buffer fills up
        // break;
        // }
        queue.remove(0);
    }
    retChannel = socketChannel.configureBlocking(false);
    // initSelector();
    Selector theSelector = this.selector;
    // int ops = ChangeRequest.CHANGEOPS;
    socketChannel.register(theSelector, ops);
    if (queue.isEmpty()) {
        // We wrote away all data, so we're no longer interested
        // in writing on this socket. Switch back to waiting for
        // data.
        key.interestOps(SelectionKey.OP_READ);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) SelectableChannel(java.nio.channels.SelectableChannel) SeekableByteArrayOutputStream(util.misc.SeekableByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ByteBuffer(java.nio.ByteBuffer) 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