Example usage for java.nio.channels SelectionKey isWritable

List of usage examples for java.nio.channels SelectionKey isWritable

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey isWritable.

Prototype

public final boolean isWritable() 

Source Link

Document

Tests whether this key's channel is ready for writing.

Usage

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);//  w w  w.j a  v a  2s  .com

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}

From source file:Main.java

public static boolean processReadySet(Set readySet) throws Exception {
    Iterator iterator = readySet.iterator();
    while (iterator.hasNext()) {
        SelectionKey key = (SelectionKey) iterator.next();
        iterator.remove();/* w  w w  .  jav  a2 s . com*/
        if (key.isConnectable()) {
            boolean connected = processConnect(key);
            if (!connected) {
                return true; // Exit
            }
        }
        if (key.isReadable()) {
            String msg = processRead(key);
            System.out.println("[Server]: " + msg);
        }
        if (key.isWritable()) {
            System.out.print("Please enter a message(Bye to quit):");
            String msg = userInputReader.readLine();

            if (msg.equalsIgnoreCase("bye")) {
                return true; // Exit
            }
            SocketChannel sChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            sChannel.write(buffer);
        }
    }
    return false; // Not done yet
}

From source file:idgs.client.TcpClient.java

private synchronized void select() throws IOException {
    if (timeout > 0) {
        if (selector.select(timeout) == 0) {
            throw new SocketTimeoutException();
        }//from  w w  w. j ava 2 s  .c  o m
    } else {
        selector.select();
    }

    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
        SelectionKey key = it.next();
        // handle connect
        if (key.isConnectable()) {
            processConnect(key);
        }
        // handle read
        else if (key.isReadable()) {
            processRead(key);
        }
        // handle write
        else if (key.isWritable()) {
            processWrite(key);
        }
        it.remove();
    }
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

protected void processKey(SelectionKey key) {
    SessionSpi session = (SessionSpi) key.attachment();

    if (key.isAcceptable())
        session.onEvent(Constants.EV_ACCEPTABLE, null);
    if (key.isConnectable())
        session.onEvent(Constants.EV_CONNECTABLE, null);
    if (key.isValid() && key.isReadable())
        session.onEvent(Constants.EV_READABLE, null);
    if (key.isValid() && key.isWritable())
        session.onEvent(Constants.EV_WRITABLE, null);
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void run() throws Exception {
    ByteBuffer recvBuffer = ByteBuffer.allocate(1100);

    while (true) {
        selector.select();/*  w  w  w .  ja  va 2  s .c om*/
        if (stopFlag) {
            return;
        }

        for (DatagramChannel channel : sendQueue.keySet()) {
            if (!sendQueue.get(channel).isEmpty()) {
                channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            } else {
                channel.register(selector, SelectionKey.OP_READ);
            }
        }

        for (SelectionKey key : selector.selectedKeys()) {
            if (!key.isValid()) {
                continue;
            }

            DatagramChannel channel = (DatagramChannel) key.channel();

            if (key.isReadable()) {
                recvBuffer.clear();
                InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer);
                recvBuffer.flip();
                for (UdpCommunicatorListener listener : listeners) {
                    try {
                        listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            } else if (key.isWritable()) {
                LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue
                        .get(channel);
                ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll();

                if (next != null) {
                    try {
                        channel.send(next.getValue(), next.getKey());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            }
        }
    }
}

From source file:net.jenet.Host.java

short socketWait(short keyType, int timeOut) {
    try {/*from  w w  w.j  a v  a2 s  . c  o  m*/
        communicationSelector.select(timeOut);
    } catch (Exception e) {
        LOG.error("Error waiting network events", e);
        return WAIT_ERROR;
    }

    for (SelectionKey key : communicationSelector.selectedKeys()) {
        if (key.isReadable() && keyType == WAIT_RECEIVE)
            return WAIT_RECEIVE;
        else if (key.isWritable() && keyType == WAIT_SEND)
            return WAIT_SEND;

    }
    return WAIT_NONE;
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * The actual NIO run loop//w ww.j  a v a2  s  .c o  m
 * 
 * @throws IOException
 */
private void process() throws IOException {

    int n = -1;

    running = true;
    update = false;
    disconnectAll = false;

    while (running) {

        try {
            n = selector.select(TIMEOUT);
        } catch (NullPointerException err) {
            continue;
        } catch (CancelledKeyException err) {
            continue;
        }

        if (!running) {
            break;
        }

        if (disconnectAll) {
            processDisconnect();
            disconnectAll = false;
            continue; // as all clients were disconnected
                      // there is nothing more to do
        }

        if (update) {
            processUpdate();
            update = false;
        }

        if (n == 0)
            continue;

        Iterator it = selector.selectedKeys().iterator();

        while (it.hasNext() && running) {
            SelectionKey sk = (SelectionKey) it.next();
            it.remove();

            try {
                if (sk.isAcceptable()) {
                    processAccept(sk);

                } else {

                    if (sk.isReadable()) {
                        try {
                            processRead(sk);
                        } catch (IOException err) {
                            cancel(sk);
                            LOG.error("An exception occured in processRead()", err);
                        }
                    } else if (sk.isWritable()) {
                        try {
                            processWrite(sk);
                        } catch (IOException err) {
                            cancel(sk);
                            LOG.error("An exception occured in processWrite()", err);
                        }
                    }
                }
            } catch (CancelledKeyException err) {
                continue;
            }
        }
    }

    // close() is in finally of run() {}
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java

/**
 * ?, ?, ?, ??/*from   w ww. j av a 2  s .  c o  m*/
 * @throws IOException
 * @throws InterruptedException
 */
private void dispatch() throws IOException, InterruptedException {
    logger.debug("try dispatch");
    SelectionKey key = null;
    key = opsChangeRequest.getChannel().keyFor(selector);
    if (key != null) {
        if ((opsChangeRequest.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
            // 
            key.interestOps(SelectionKey.OP_WRITE);
            opsChangeRequest.clearOps(SelectionKey.OP_WRITE);
        } else if ((opsChangeRequest.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
            key.interestOps(SelectionKey.OP_READ);
            opsChangeRequest.clearOps(SelectionKey.OP_READ);
        }
    }

    // ?,  
    isWeakuped.set(false);
    if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) {
        return;
    }

    // ?
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        key = (SelectionKey) iterator.next();
        iterator.remove();
        if (!key.isValid()) {
            continue;
        } else if (key.isReadable()) {
            onRead(key);
        } else if (key.isWritable()) {
            onWrite(key);
        }
    }
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

private void dispatch() throws IOException {
    logger.debug("try dispatch");
    SelectionKey key = null;
    for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) {
        key = request.getChannel().keyFor(selector);
        if (key != null) {
            // /*from   w  w  w .  j  a v a  2  s .  c  o m*/
            if ((request.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                key.interestOps(SelectionKey.OP_WRITE);
                request.clearOps(SelectionKey.OP_WRITE);
            } else if ((request.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                key.interestOps(SelectionKey.OP_READ);
                request.clearOps(SelectionKey.OP_READ);
            }
        }
    }

    isWeakuped.set(false);
    if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) {
        return;
    }

    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        key = (SelectionKey) iterator.next();
        iterator.remove();
        try {
            if (!key.isValid()) {
                continue;
            } else if (key.isAcceptable()) {
                onAccept(key);
            } else if (key.isReadable()) {
                //readerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_READ));
                onRead(key);
            } else if (key.isWritable()) {
                //writerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_WRITE));
                onWrite(key);
            }
        } catch (IOException e) {
            // 
            opsChangeRequstMap.remove((SocketChannel) key.channel());
            Session session = (Session) key.attachment();
            if (session != null) {
                session.onException(e);
                // Session
                sessionManager.freeSession(session);
            }
            key.cancel();
            key.channel().close();
            e.printStackTrace();
            logger.error("OOPSException", e);
        }
    }
}

From source file:jp.queuelinker.system.net.SelectorThread.java

@Override
public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    // I believe the inner try-catches does not cause overhead.
    // http://stackoverflow.com/questions/141560/
    long sendCount = 0;

    SocketChannel currentChannel;
    SelectionKey key = null;
    while (true) {
        try {/*  www .  j a v a2 s  .  com*/
            selector.select();
            // selector.selectNow();
        } catch (ClosedSelectorException e) {
            logger.fatal("BUG: The selector is closed.");
            return;
        } catch (IOException e) {
            logger.fatal("An IOException occured while calling select().");
            // Fatal Error. Notify the error to the users and leave the matter to them.
            for (ChannelState state : channels) {
                state.callBack.fatalError();
            }
            return;
        }

        if (!requests.isEmpty()) {
            handleRequest();
            continue;
        }

        if (stopRequested) {
            return;
        }

        Set<SelectionKey> keys = selector.selectedKeys();

        Iterator<SelectionKey> iter = keys.iterator();
        iter_loop: while (iter.hasNext()) {
            key = iter.next();
            iter.remove(); // Required. Don't remove.

            if (key.isReadable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                int valid;
                try {
                    valid = currentChannel.read(buffer);
                } catch (IOException e) {
                    logger.warn("An IOException happened while reading from a channel.");
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    key.cancel();
                    continue;
                }
                if (valid == -1) {
                    // Normal socket close?
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    // cleanUpChannel(state.channelId);
                    key.cancel();
                    continue;
                }

                buffer.rewind();
                if (state.callBack.receive(state.channelId, buffer, valid, state.attachment) == false) {
                    state.key.interestOps(state.key.interestOps() & ~SelectionKey.OP_READ);
                }
                buffer.clear();
            } else if (key.isWritable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                while (state.sendBuffer.readableSize() < WRITE_SIZE) {
                    ByteBuffer newBuffer = state.callBack.send(state.channelId, state.attachment);
                    if (newBuffer != null) {
                        state.sendBuffer.write(newBuffer);
                        if (++sendCount % 50000 == 0) {
                            logger.info("Send Count: " + sendCount);
                        }
                    } else if (state.sendBuffer.readableSize() == 0) {
                        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                        continue iter_loop;
                    } else {
                        break;
                    }
                }

                final int available = state.sendBuffer.readableSize();
                if (available >= WRITE_SIZE || ++state.noopCount >= HEURISTIC_WAIT) {
                    int done;
                    try {
                        done = currentChannel.write(state.sendBuffer.getByteBuffer());
                    } catch (IOException e) {
                        logger.warn("An IOException occured while writing to a channel.");
                        state.callBack.exceptionOccured(state.channelId, state.attachment);
                        key.cancel();
                        continue;
                    }
                    if (done < available) {
                        state.sendBuffer.rollback(available - done);
                    }
                    state.sendBuffer.compact();
                    state.noopCount = 0;
                }
            } else if (key.isAcceptable()) {
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                ChannelState state = (ChannelState) key.attachment();
                SocketChannel socketChannel;
                try {
                    socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                } catch (IOException e) {
                    continue; // Do nothing.
                }
                state.callBack.newConnection(state.channelId, socketChannel, state.attachment);
            }
        }
    }
}