Search in sources :

Example 71 with SelectionKey

use of java.nio.channels.SelectionKey in project CshBBrain by CshBBrain.

the class MasterServer method startMonitor.

/**
	 * 
	 * <li>方法名:startMonitor
	 * <li>
	 * <li>返回类型:void
	 * <li>说明:开始监听业务请求处理
	 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
	 * <li>创建日期:2011-9-28
	 * <li>修改人: 
	 * <li>修改日期:
	 */
private void startMonitor() {
    try {
        // Create a new selector
        Selector selector = Selector.open();
        // Create a new non-blocking server socket channel
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        InetSocketAddress isa = new InetSocketAddress(this.port);
        serverChannel.socket().bind(isa);
        // Register the server socket channel, indicating an interest in 
        // accepting new connections
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        log.info("服务器准备就绪,等待请求到来");
        while (noStopRequested) {
            try {
                int num = 0;
                // Wait for an event one of the registered channels
                num = selector.select(100);
                if (num > 0) {
                    // Iterate over the set of keys for which events are available
                    Iterator selectedKeys = selector.selectedKeys().iterator();
                    while (selectedKeys.hasNext()) {
                        SelectionKey key = (SelectionKey) selectedKeys.next();
                        selectedKeys.remove();
                        if (!key.isValid()) {
                            continue;
                        }
                        // Check what event is available and deal with it
                        if (key.isAcceptable()) {
                            this.accept(key, false);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 关闭服务器
        serverChannel.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Server start up fail");
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) Iterator(java.util.Iterator) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) Selector(java.nio.channels.Selector)

Example 72 with SelectionKey

use of java.nio.channels.SelectionKey in project CloudStack-archive by CloudStack-extras.

the class NioConnection method run.

@Override
public void run() {
    synchronized (_thread) {
        try {
            init();
        } catch (ConnectException e) {
            s_logger.error("Unable to connect to remote");
            return;
        } catch (IOException e) {
            s_logger.error("Unable to initialize the threads.", e);
            return;
        } catch (Exception e) {
            s_logger.error("Unable to initialize the threads due to unknown exception.", e);
            return;
        }
        _isStartup = true;
        _thread.notifyAll();
    }
    while (_isRunning) {
        try {
            _selector.select();
            // Someone is ready for I/O, get the ready keys
            Set<SelectionKey> readyKeys = _selector.selectedKeys();
            Iterator<SelectionKey> i = readyKeys.iterator();
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Keys Processing: " + readyKeys.size());
            }
            // Walk through the ready keys collection.
            while (i.hasNext()) {
                SelectionKey sk = i.next();
                i.remove();
                if (!sk.isValid()) {
                    if (s_logger.isTraceEnabled()) {
                        s_logger.trace("Selection Key is invalid: " + sk.toString());
                    }
                    Link link = (Link) sk.attachment();
                    if (link != null) {
                        link.terminated();
                    } else {
                        closeConnection(sk);
                    }
                } else if (sk.isReadable()) {
                    read(sk);
                } else if (sk.isWritable()) {
                    write(sk);
                } else if (sk.isAcceptable()) {
                    accept(sk);
                } else if (sk.isConnectable()) {
                    connect(sk);
                }
            }
            s_logger.trace("Keys Done Processing.");
            processTodos();
        } catch (Throwable e) {
            s_logger.warn("Caught an exception but continuing on.", e);
        }
    }
    synchronized (_thread) {
        _isStartup = false;
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException) CancelledKeyException(java.nio.channels.CancelledKeyException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 73 with SelectionKey

use of java.nio.channels.SelectionKey in project CloudStack-archive by CloudStack-extras.

the class NioConnection method processTodos.

protected void processTodos() {
    List<ChangeRequest> todos;
    if (_todos.size() == 0) {
        // Nothing to do.
        return;
    }
    synchronized (this) {
        todos = _todos;
        _todos = new ArrayList<ChangeRequest>();
    }
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Todos Processing: " + todos.size());
    }
    SelectionKey key;
    for (ChangeRequest todo : todos) {
        switch(todo.type) {
            case ChangeRequest.CHANGEOPS:
                try {
                    key = (SelectionKey) todo.key;
                    if (key != null && key.isValid()) {
                        if (todo.att != null) {
                            key.attach(todo.att);
                            Link link = (Link) todo.att;
                            link.setKey(key);
                        }
                        key.interestOps(todo.ops);
                    }
                } catch (CancelledKeyException e) {
                    s_logger.debug("key has been cancelled");
                }
                break;
            case ChangeRequest.REGISTER:
                try {
                    key = ((SocketChannel) (todo.key)).register(_selector, todo.ops, todo.att);
                    if (todo.att != null) {
                        Link link = (Link) todo.att;
                        link.setKey(key);
                    }
                } catch (ClosedChannelException e) {
                    s_logger.warn("Couldn't register socket: " + todo.key);
                    try {
                        ((SocketChannel) (todo.key)).close();
                    } catch (IOException ignore) {
                    } finally {
                        Link link = (Link) todo.att;
                        link.terminated();
                    }
                }
                break;
            case ChangeRequest.CLOSE:
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Trying to close " + todo.key);
                }
                key = (SelectionKey) todo.key;
                closeConnection(key);
                if (key != null) {
                    Link link = (Link) key.attachment();
                    if (link != null) {
                        link.terminated();
                    }
                }
                break;
            default:
                s_logger.warn("Shouldn't be here");
                throw new RuntimeException("Shouldn't be here");
        }
    }
    s_logger.trace("Todos Done processing");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ClosedChannelException(java.nio.channels.ClosedChannelException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException)

Example 74 with SelectionKey

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

the class ZMQ method poll.

/**
     * Polling on items with given selector
     * CAUTION: This could be affected by jdk epoll bug
     *
     * @param selector Open and reuse this selector and do not forget to close when it is not used.
     * @param items
     * @param count
     * @param timeout
     * @return number of events
     */
public static int poll(Selector selector, PollItem[] items, int count, long timeout) {
    if (items == null) {
        throw new IllegalArgumentException();
    }
    if (count == 0) {
        if (timeout <= 0) {
            return 0;
        }
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
        }
        return 0;
    }
    long now = 0L;
    long end = 0L;
    HashMap<SelectableChannel, SelectionKey> saved = new HashMap<SelectableChannel, SelectionKey>();
    for (SelectionKey key : selector.keys()) {
        if (key.isValid()) {
            saved.put(key.channel(), key);
        }
    }
    for (int i = 0; i < count; i++) {
        PollItem item = items[i];
        if (item == null) {
            continue;
        }
        // mailbox channel if ZMQ socket
        SelectableChannel ch = item.getChannel();
        SelectionKey key = saved.remove(ch);
        if (key != null) {
            if (key.interestOps() != item.interestOps()) {
                key.interestOps(item.interestOps());
            }
            key.attach(item);
        } else {
            try {
                ch.register(selector, item.interestOps(), item);
            } catch (ClosedChannelException e) {
                throw new ZError.IOException(e);
            }
        }
    }
    if (!saved.isEmpty()) {
        for (SelectionKey deprecated : saved.values()) {
            deprecated.cancel();
        }
    }
    boolean firstPass = true;
    int nevents = 0;
    int ready;
    while (true) {
        //  Compute the timeout for the subsequent poll.
        long waitMillis;
        if (firstPass) {
            waitMillis = 0L;
        } else if (timeout < 0L) {
            waitMillis = -1L;
        } else {
            waitMillis = end - now;
        }
        //  Wait for events.
        try {
            int rc = 0;
            if (waitMillis < 0) {
                rc = selector.select(0);
            } else if (waitMillis == 0) {
                rc = selector.selectNow();
            } else {
                rc = selector.select(waitMillis);
            }
            for (SelectionKey key : selector.keys()) {
                PollItem item = (PollItem) key.attachment();
                ready = item.readyOps(key, rc);
                if (ready < 0) {
                    return -1;
                }
                if (ready > 0) {
                    nevents++;
                }
            }
            selector.selectedKeys().clear();
        } catch (IOException e) {
            throw new ZError.IOException(e);
        }
        //  If timeout is zero, exit immediately whether there are events or not.
        if (timeout == 0) {
            break;
        }
        if (nevents > 0) {
            break;
        }
        //  If timeout is infinite we can just loop until we get some events.
        if (timeout < 0) {
            if (firstPass) {
                firstPass = false;
            }
            continue;
        }
        //  when the polling should time out.
        if (firstPass) {
            now = Clock.nowMS();
            end = now + timeout;
            if (now == end) {
                break;
            }
            firstPass = false;
            continue;
        }
        //  Find out whether timeout have expired.
        now = Clock.nowMS();
        if (now >= end) {
            break;
        }
    }
    return nevents;
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ClosedChannelException(java.nio.channels.ClosedChannelException) HashMap(java.util.HashMap) IOException(java.io.IOException) SelectableChannel(java.nio.channels.SelectableChannel)

Example 75 with SelectionKey

use of java.nio.channels.SelectionKey in project wifikeyboard by IvanVolosyuk.

the class HttpServer method run.

@Override
public void run() {
    //    Debug.d("HttpServer started listening");
    try {
        ch.configureBlocking(false);
        SelectionKey serverkey = ch.register(selector, SelectionKey.OP_ACCEPT);
        final ArrayList<Update> newUpdates = new ArrayList<Update>();
        Action checkUpdates = new Action() {

            @Override
            public Object run() {
                for (Update u : pendingUpdates) {
                    newUpdates.add(u);
                }
                pendingUpdates.clear();
                return null;
            }
        };
        while (true) {
            newUpdates.clear();
            runAction(checkUpdates);
            for (Update u : newUpdates) {
                u.run();
            }
            //        Debug.d("waiting for event");
            selector.select();
            //        Debug.d("got an event");
            Set<SelectionKey> keys = selector.selectedKeys();
            for (Iterator<SelectionKey> i = keys.iterator(); i.hasNext(); ) {
                SelectionKey key = i.next();
                i.remove();
                if (key == serverkey) {
                    if (key.isAcceptable()) {
                        SocketChannel client = ch.accept();
                        //              Debug.d("NEW CONNECTION from " + client.socket().getRemoteSocketAddress());
                        client.configureBlocking(false);
                        SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                        HttpConnection con = newConnection(client);
                        clientkey.attach(con);
                        con.setKey(clientkey);
                    }
                } else {
                    HttpConnection conn = (HttpConnection) key.attachment();
                    try {
                        HttpConnection.ConnectionState prevState, newState;
                        if (key.isReadable()) {
                            prevState = HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_NEW_INPUT;
                            //                Debug.d("processing read event");
                            //                long start = System.currentTimeMillis();
                            newState = conn.newInput();
                        //                long end = System.currentTimeMillis();
                        //                Debug.d("delay = " + (end - start));
                        //                int size = android.os.Debug.getThreadAllocSize();
                        //                android.os.Debug.stopAllocCounting();
                        //                Log.d("wifikeyboard", "finished read event, allocs = " + size);
                        //                android.os.Debug.startAllocCounting();
                        } else if (key.isWritable()) {
                            prevState = HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_OUTPUT_BUFFER;
                            //                Debug.d("processing write event");
                            newState = conn.newOutputBuffer();
                        //                Log.d("wifikeyboard", "finished write event");
                        } else {
                            continue;
                        }
                        if (newState == prevState)
                            continue;
                        key.interestOps((newState == HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_NEW_INPUT ? SelectionKey.OP_READ : 0) | (newState == HttpConnection.ConnectionState.SELECTOR_WAIT_FOR_OUTPUT_BUFFER ? SelectionKey.OP_WRITE : 0));
                    } catch (IOException io) {
                        //                  conn.getClient().socket().getRemoteSocketAddress());
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    } catch (ConnectionFailureException e) {
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    } catch (NumberFormatException e) {
                        // FIXME: move to ConnectionFailureException
                        if (key != null)
                            key.cancel();
                        conn.getClient().close();
                    }
                }
            }
        }
    } catch (IOException e) {
        Debug.e("network loop terminated", e);
    } catch (NetworkThreadStopException e) {
        Debug.e("network thread stop requested", e);
    }
    try {
        selector.close();
    } catch (Throwable t) {
    }
    try {
        ch.close();
    } catch (Throwable t) {
    }
    onExit();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ConnectionFailureException(com.volosyukivan.HttpConnection.ConnectionFailureException)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5