Example usage for java.nio.channels Selector select

List of usage examples for java.nio.channels Selector select

Introduction

In this page you can find the example usage for java.nio.channels Selector select.

Prototype

public int select(Consumer<SelectionKey> action) throws IOException 

Source Link

Document

Selects and performs an action on the keys whose corresponding channels are ready for I/O operations.

Usage

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private SelectionKey selectFirstConnectedSocketChannel(Selector selector) throws IOException {
    log.trace("selectFirstConnectedSocketChannel()");

    while (!selector.keys().isEmpty()) {
        if (selector.select(connectTimeout) == 0) { // Block until something happens
            return null;
        }//from ww  w.  ja  v  a  2  s. com

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            if (key.isValid() && key.isConnectable()) {
                SocketChannel channel = (SocketChannel) key.channel();
                try {
                    if (channel.finishConnect()) {
                        return key;
                    }
                } catch (Exception e) {
                    key.cancel();
                    closeQuietly(channel);

                    log.trace("Error connecting socket channel: {}", e);
                }
            }

            it.remove();
        }
    }

    return null;
}

From source file:co.elastic.tealess.SSLChecker.java

private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) {
    final InetSocketAddress address = sslReport.getAddress();
    try {//www.  j  a  va 2s  . c  o  m
        logger.trace("Connecting to {}", address);
        Selector selector = Selector.open();
        SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT);
        socket.connect(address);
        selector.select(timeout);
        if (!sk.isConnectable()) {
            sslReport.setFailed(new SocketTimeoutException());
            return;
        }
        if (socket.isConnectionPending()) {
            socket.finishConnect();
        }
    } catch (ConnectException e) {
        logger.debug("Connection failed to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    } catch (IOException e) {
        logger.error("Failed connecting to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    }

    logger.debug("Connection successful to {}", address);
}

From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java

public void listen() throws Exception {
    doListen = true;//from  ww  w  .  ja va  2  s .  c  o m
    // allocate an unbound server socket channel
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    Selector selector = Selector.open();
    // set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(bind, port));
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (doListen) {
        // this may block for a long time, upon return the
        // selected set contains keys of the ready channels
        try {

            //System.out.println("Selecting with timeout="+timeout);
            int n = selector.select(timeout);
            //System.out.println("select returned="+n);
            if (n == 0) {
                continue; // nothing to do
            }
            // get an iterator over the set of selected keys
            Iterator it = selector.selectedKeys().iterator();
            // look at each key in the selected set
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                // Is a new connection coming in?
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    registerChannel(selector, channel, SelectionKey.OP_READ,
                            new ObjectReader(channel, selector, callback));
                }
                // is there data to read on this channel?
                //System.out.println("key readable="+key.isReadable());
                if (key.isReadable()) {
                    readDataFromSocket(key);
                } else {
                    //System.out.println("This shouldn't get called");
                    key.interestOps(key.interestOps() & (~key.OP_WRITE));
                }

                // remove key from selected set, it's been handled
                it.remove();
            }
            //System.out.println("Done with loop");
        } catch (java.nio.channels.CancelledKeyException nx) {
            log.warn("Replication client disconnected, error when polling key. Ignoring client.");
        } catch (Exception x) {
            log.error("Unable to process request in ReplicationListener", x);
        }

    } //while
    serverChannel.close();
    selector.close();
}

From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java

@Override
public void run() {
    Selector socketSelector;
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

    try {//from  ww w.j av  a2s . c  om
        // Create a non-blocking socket channel
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        socketChannel.socket().setReceiveBufferSize(32768);
        socketChannel.socket().setSoLinger(true, 1);
        socketChannel.socket().setSoTimeout(0x15f90);
        socketChannel.socket().setReuseAddress(true);

        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(server, port));

        // Create a new selector
        socketSelector = SelectorProvider.provider().openSelector();

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$
                e);
        Activator.log(status);
        return;
    }

    for (;;) {
        try {
            if (socketSelector.select(30 * 1000) == 0) {
                logger.trace(">" + HEARTBEAT); //$NON-NLS-1$
                socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$
            }
        } catch (Exception e) {
            break;
        }

        // Iterate over the set of keys for which events are available
        Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
            SelectionKey key = selectedKeys.next();
            selectedKeys.remove();

            if (!key.isValid()) {
                continue;
            }

            try {
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    // Finish the connection. If the connection operation failed
                    // this will raise an IOException.
                    try {
                        socketChannel.finishConnect();
                    } catch (IOException e) {
                        // Cancel the channel's registration with our selector
                        key.cancel();
                        return;
                    }

                    // Register an interest in writing on this channel
                    key.interestOps(SelectionKey.OP_WRITE);
                }
                if (key.isWritable()) {
                    logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$
                    socketChannel.write(ByteBuffer.wrap(
                            new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$

                    // Register an interest in reading on this channel
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    dst.clear();
                    int readed = socketChannel.read(dst);
                    if (readed > 0) {
                        String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$
                        for (int i = 0; i < s.length; i++) {
                            logger.trace("<" + s[i]); //$NON-NLS-1$

                            if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$
                                logger.trace(">" + UNKNOWN70); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$
                                logger.trace(">" + UNKNOWN55); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$
                            }

                            if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
                                try {
                                    OrderMonitor monitor = parseOrderLine(s[i]);

                                    OrderDelta[] delta;
                                    synchronized (orders) {
                                        if (!orders.contains(monitor)) {
                                            orders.add(monitor);
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_ADDED, monitor) };
                                        } else {
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_UPDATED, monitor) };
                                        }
                                    }
                                    fireUpdateNotifications(delta);

                                    if (monitor.getFilledQuantity() != null
                                            && monitor.getAveragePrice() != null) {
                                        Account account = WebConnector.getInstance().getAccount();
                                        account.updatePosition(monitor);
                                    }
                                } catch (ParseException e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$
                                updateStatusLine(s[i]);
                            }
                            if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$
                                try {
                                    positions.add(new Position(s[i]));
                                } catch (Exception e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$
                                Account account = WebConnector.getInstance().getAccount();
                                account.setPositions(positions.toArray(new Position[positions.size()]));
                                positions.clear();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$
                Activator.log(status);
            }
        }
    }
}