Search in sources :

Example 71 with Selector

use of java.nio.channels.Selector in project Mycat-Server by MyCATApache.

the class NIOConnector method run.

@Override
public void run() {
    final Selector tSelector = this.selector;
    for (; ; ) {
        ++connectCount;
        try {
            tSelector.select(1000L);
            connect(tSelector);
            Set<SelectionKey> keys = tSelector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid() && key.isConnectable()) {
                        finishConnect(key, att);
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Exception e) {
            LOGGER.warn(name, e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 72 with Selector

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

the class HackSelectReceiveSendUdpPong method run.

private void run() throws IOException {
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final NioSelectedKeySet keySet = Common.keySet(selector);
    final ToIntFunction<SelectionKey> handler = (key) -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
            buffer.clear();
            buffer.putLong(receivedSequenceNumber);
            buffer.putLong(receivedTimestamp);
            buffer.flip();
            sendChannel.send(buffer, sendAddress);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, null);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (true) {
        while (selector.selectNow() == 0) {
            if (!running.get()) {
                return;
            }
        }
        keySet.forEach(handler);
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) DatagramChannel(java.nio.channels.DatagramChannel) Selector(java.nio.channels.Selector) ToIntFunction(java.util.function.ToIntFunction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) SigInt(org.agrona.concurrent.SigInt) ByteBuffer(java.nio.ByteBuffer) SIZE_OF_LONG(org.agrona.BitUtil.SIZE_OF_LONG) Configuration(io.aeron.driver.Configuration) NioSelectedKeySet(org.agrona.nio.NioSelectedKeySet) OP_READ(java.nio.channels.SelectionKey.OP_READ) SelectionKey(java.nio.channels.SelectionKey) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioSelectedKeySet(org.agrona.nio.NioSelectedKeySet) InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Selector(java.nio.channels.Selector)

Example 73 with Selector

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

the class SelectReceiveSendUdpPong method run.

private void run() throws IOException {
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_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 receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
            buffer.clear();
            buffer.putLong(receivedSequenceNumber);
            buffer.putLong(receivedTimestamp);
            buffer.flip();
            sendChannel.send(buffer, sendAddress);
        } 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 (true) {
        while (selector.selectNow() == 0) {
            if (!running.get()) {
                return;
            }
        }
        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext()) {
            final SelectionKey key = iter.next();
            if (key.isReadable()) {
                ((IntSupplier) key.attachment()).getAsInt();
            }
            iter.remove();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SelectionKey(java.nio.channels.SelectionKey) 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 74 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 75 with Selector

use of java.nio.channels.Selector in project jeromq by zeromq.

the class Proxy method proxy.

public static boolean proxy(SocketBase frontend, SocketBase backend, SocketBase capture) {
    //  The algorithm below assumes ratio of requests and replies processed
    //  under full load to be 1:1.
    //  TODO: The current implementation drops messages when
    //  any of the pipes becomes full.
    boolean success = true;
    int rc;
    long more;
    Msg msg;
    PollItem[] items = new PollItem[2];
    items[0] = new PollItem(frontend, ZMQ.ZMQ_POLLIN);
    items[1] = new PollItem(backend, ZMQ.ZMQ_POLLIN);
    Selector selector;
    try {
        selector = Selector.open();
    } catch (IOException e) {
        throw new ZError.IOException(e);
    }
    try {
        while (!Thread.currentThread().isInterrupted()) {
            //  Wait while there are either requests or replies to process.
            rc = ZMQ.poll(selector, items, -1);
            if (rc < 0) {
                return false;
            }
            //  Process a request.
            if (items[0].isReadable()) {
                while (true) {
                    msg = frontend.recv(0);
                    if (msg == null) {
                        return false;
                    }
                    more = frontend.getSocketOpt(ZMQ.ZMQ_RCVMORE);
                    if (more < 0) {
                        return false;
                    }
                    //  Copy message to capture socket if any
                    if (capture != null) {
                        Msg ctrl = new Msg(msg);
                        success = capture.send(ctrl, more > 0 ? ZMQ.ZMQ_SNDMORE : 0);
                        if (!success) {
                            return false;
                        }
                    }
                    success = backend.send(msg, more > 0 ? ZMQ.ZMQ_SNDMORE : 0);
                    if (!success) {
                        return false;
                    }
                    if (more == 0) {
                        break;
                    }
                }
            }
            //  Process a reply.
            if (items[1].isReadable()) {
                while (true) {
                    msg = backend.recv(0);
                    if (msg == null) {
                        return false;
                    }
                    more = backend.getSocketOpt(ZMQ.ZMQ_RCVMORE);
                    if (more < 0) {
                        return false;
                    }
                    //  Copy message to capture socket if any
                    if (capture != null) {
                        Msg ctrl = new Msg(msg);
                        success = capture.send(ctrl, more > 0 ? ZMQ.ZMQ_SNDMORE : 0);
                        if (!success) {
                            return false;
                        }
                    }
                    success = frontend.send(msg, more > 0 ? ZMQ.ZMQ_SNDMORE : 0);
                    if (!success) {
                        return false;
                    }
                    if (more == 0) {
                        break;
                    }
                }
            }
        }
    } finally {
        try {
            selector.close();
        } catch (Exception e) {
        }
    }
    return true;
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Aggregations

Selector (java.nio.channels.Selector)85 SelectionKey (java.nio.channels.SelectionKey)43 IOException (java.io.IOException)26 SocketChannel (java.nio.channels.SocketChannel)24 InetSocketAddress (java.net.InetSocketAddress)17 ServerSocketChannel (java.nio.channels.ServerSocketChannel)17 ByteBuffer (java.nio.ByteBuffer)10 ClosedChannelException (java.nio.channels.ClosedChannelException)8 DatagramChannel (java.nio.channels.DatagramChannel)8 CancelledKeyException (java.nio.channels.CancelledKeyException)6 ClosedSelectorException (java.nio.channels.ClosedSelectorException)4 SelectableChannel (java.nio.channels.SelectableChannel)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Test (org.junit.Test)4 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)3 BigDecimal (java.math.BigDecimal)2 ConnectException (java.net.ConnectException)2 DatagramPacket (java.net.DatagramPacket)2 DatagramSocket (java.net.DatagramSocket)2 InetAddress (java.net.InetAddress)2