Example usage for java.nio.channels SelectionKey OP_WRITE

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

Introduction

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

Prototype

int OP_WRITE

To view the source code for java.nio.channels SelectionKey OP_WRITE.

Click Source Link

Document

Operation-set bit for write operations.

Usage

From source file:com.ok2c.lightmtp.impl.protocol.ExtendedSendHeloCodec.java

@Override
public void consumeData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionInputBuffer buf = this.iobuffers.getInbuf();

    int bytesRead = buf.fill(iosession.channel());
    SMTPReply reply = this.parser.parse(buf, bytesRead == -1);

    if (reply != null) {
        switch (this.codecState) {
        case SERVICE_READY_EXPECTED:
            if (reply.getCode() == SMTPCodes.SERVICE_READY) {
                this.codecState = CodecState.EHLO_READY;
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                this.codecState = CodecState.COMPLETED;
                sessionState.setReply(reply);
            }/*from  w w  w  . j a  v  a 2  s. co m*/
            break;
        case EHLO_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.OK) {

                Set<String> extensions = sessionState.getExtensions();

                List<String> lines = reply.getLines();
                if (lines.size() > 1) {
                    for (int i = 1; i < lines.size(); i++) {
                        String line = lines.get(i);
                        extensions.add(line.toUpperCase(Locale.US));
                    }
                }
                this.codecState = CodecState.COMPLETED;
                sessionState.setReply(reply);
            } else if (reply.getCode() == SMTPCodes.ERR_PERM_SYNTAX_ERR_COMMAND) {
                this.codecState = CodecState.HELO_READY;
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                this.codecState = CodecState.COMPLETED;
                sessionState.setReply(reply);
            }
            break;
        case HELO_RESPONSE_EXPECTED:
            this.codecState = CodecState.COMPLETED;
            sessionState.setReply(reply);
            break;
        default:
            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                sessionState.setReply(reply);
                this.codecState = CodecState.COMPLETED;
            } else {
                throw new SMTPProtocolException("Unexpected reply: " + reply);
            }
        }
    } else {
        if (bytesRead == -1 && !sessionState.isTerminated()) {
            throw new UnexpectedEndOfStreamException();
        }
    }
}

From source file:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {// w  w w  .  j a  v  a 2  s. c  om
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}

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

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

    while (true) {
        selector.select();/*from   w  ww  .  j a v  a  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:com.ok2c.lightmtp.impl.protocol.PipeliningReceiveEnvelopCodec.java

@Override
public void produceData(final IOSession iosession, final ServerState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    synchronized (sessionState) {

        if (this.actionFuture != null) {
            SMTPReply reply = getReply(this.actionFuture);
            this.actionFuture = null;
            this.writer.write(reply, buf);
        }/*from ww w .j a va 2  s .  co m*/

        if (this.actionFuture == null) {
            while (!this.pendingActions.isEmpty()) {
                Action<ServerState> action = this.pendingActions.remove();
                Future<SMTPReply> future = action.execute(sessionState,
                        new OutputTrigger<SMTPReply>(sessionState, iosession));
                if (future.isDone()) {
                    SMTPReply reply = getReply(future);
                    this.writer.write(reply, buf);
                } else {
                    this.actionFuture = future;
                    break;
                }
            }
        }

        if (buf.hasData()) {
            buf.flush(iosession.channel());
        }
        if (!buf.hasData()) {
            if (sessionState.getDataType() != null) {
                this.completed = true;
            }
            if (sessionState.isTerminated()) {
                iosession.close();
            } else {
                iosession.clearEvent(SelectionKey.OP_WRITE);
            }
        }
    }
}

From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java

@Override
public void run() {
    try {//from ww  w  .j a v a 2 s  .  c om
        Log.get().log(Level.INFO, "Server listening on port {0}", port);

        // Create a Selector that handles the SocketChannel multiplexing
        final Selector readSelector = Selector.open();
        final Selector writeSelector = Selector.open();

        // Start working threads
        final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors());
        ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
        for (int n = 0; n < workerThreads; n++) {
            cworkers[n] = new ConnectionWorker();
            cworkers[n].start();
        }
        Log.get().log(Level.INFO, "{0} worker threads started.", workerThreads);

        ChannelWriter.getInstance().setSelector(writeSelector);
        ChannelReader.getInstance().setSelector(readSelector);
        ChannelWriter.getInstance().start();
        ChannelReader.getInstance().start();

        final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(true); // Set to blocking mode

        // Configure ServerSocket; bind to socket...
        serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(this.port));

        while (isRunning()) {
            SocketChannel socketChannel;

            try {
                // As we set the server socket channel to blocking mode the
                // accept()
                // method will block.
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                assert socketChannel.isConnected();
                assert socketChannel.finishConnect();
            } catch (IOException ex) {
                // Under heavy load an IOException "Too many open files may
                // be thrown. It most cases we should slow down the
                // connection accepting, to give the worker threads some
                // time to process work.
                Log.get().log(Level.SEVERE, "IOException while accepting connection: {0}", ex.getMessage());
                Log.get().info("Connection accepting sleeping for seconds...");
                Thread.sleep(5000); // 5 seconds
                continue;
            }

            //FIXME conn should be NNTPConnection
            final SynchronousNNTPConnection conn = (SynchronousNNTPConnection) context
                    .getBean("syncNNTPConnection", NNTPConnection.class);
            conn.setChannelWrapper(new SocketChannelWrapperFactory(socketChannel).create());
            Connections.getInstance().add(conn);

            try {
                SelectionKey selKeyWrite = registerSelector(writeSelector, socketChannel,
                        SelectionKey.OP_WRITE);
                registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);

                Log.get().log(Level.INFO, "Connected: {0}", socketChannel.socket().getRemoteSocketAddress());

                // Set write selection key and send hello to client
                conn.setWriteSelectionKey(selKeyWrite);
                conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost") + " <unknown version>" // + Application.VERSION
                        + " news server ready - (posting ok).");
            } catch (CancelledKeyException cke) {
                Log.get().log(Level.WARNING, "CancelledKeyException {0} was thrown: {1}",
                        new Object[] { cke.getMessage(), socketChannel.socket() });
            } catch (ClosedChannelException cce) {
                Log.get().log(Level.WARNING, "ClosedChannelException {0} was thrown: {1}",
                        new Object[] { cce.getMessage(), socketChannel.socket() });
            }
        }
    } catch (BindException ex) {
        // Could not bind to socket; this is a fatal, so perform a shutdown
        Log.get().log(Level.SEVERE, ex.getLocalizedMessage() + " -> shutdown sonews", ex);
        setRunning(false);
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

private void onEnableWrite() {
    if (writeKey != null && writeKey.isValid()) {
        writeKey.interestOps(writeKey.interestOps() | SelectionKey.OP_WRITE);
    }
}

From source file:me.xingrz.prox.tcp.tunnel.Tunnel.java

protected void keepRemaining(ByteBuffer buffer) {
    remaining.clear();/*from  ww w.  ja v  a  2 s  .  co  m*/
    remaining.put(buffer);
    remaining.flip();

    // ??????
    if (!channel.isConnected()) {
        return;
    }

    try {
        channel.register(selector, SelectionKey.OP_WRITE, this);
    } catch (ClosedChannelException e) {
        logger.w(e, "Failed to register OP_WRITE since channel is closed");
        IOUtils.closeQuietly(this);
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.SimpleSendEnvelopCodec.java

@Override
public void consumeData(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(sessionState, "Session state");

    SessionInputBuffer buf = this.iobuffers.getInbuf();
    DeliveryRequest request = sessionState.getRequest();

    int bytesRead = buf.fill(iosession.channel());
    SMTPReply reply = this.parser.parse(buf, bytesRead == -1);

    if (reply != null) {
        switch (this.codecState) {
        case MAIL_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.OK) {
                this.codecState = CodecState.RCPT_REQUEST_READY;
                this.recipients.clear();
                this.recipients.addAll(request.getRecipients());
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                this.deliveryFailed = true;
                this.codecState = CodecState.COMPLETED;
                sessionState.setReply(reply);
            }// w  w w.j a v  a 2 s .  c  om
            break;
        case RCPT_RESPONSE_EXPECTED:
            if (this.recipients.isEmpty()) {
                throw new IllegalStateException("Unexpected state: " + this.codecState);
            }
            String recipient = this.recipients.removeFirst();

            if (reply.getCode() != SMTPCodes.OK) {
                sessionState.getFailures().add(new RcptResult(reply, recipient));
            }

            if (this.recipients.isEmpty()) {
                List<String> requested = request.getRecipients();
                List<RcptResult> failured = sessionState.getFailures();
                if (requested.size() > failured.size()) {
                    this.codecState = CodecState.DATA_REQUEST_READY;
                } else {
                    this.deliveryFailed = true;
                    this.codecState = CodecState.COMPLETED;
                    sessionState.setReply(reply);
                }
            } else {
                this.codecState = CodecState.RCPT_REQUEST_READY;
            }
            iosession.setEvent(SelectionKey.OP_WRITE);
            break;
        case DATA_RESPONSE_EXPECTED:
            this.codecState = CodecState.COMPLETED;
            if (reply.getCode() != SMTPCodes.START_MAIL_INPUT) {
                this.deliveryFailed = true;
            }
            sessionState.setReply(reply);
            break;
        default:
            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                sessionState.setReply(reply);
                this.codecState = CodecState.COMPLETED;
            } else {
                throw new SMTPProtocolException("Unexpected reply: " + reply);
            }
        }
    }

    if (bytesRead == -1 && !sessionState.isTerminated()) {
        throw new UnexpectedEndOfStreamException();
    }
}

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

@Override
public boolean notifyWrite(SocketChannel channel) {
    logger.debug("notifyWrite");
    if (state.get() == NetworkStateEnum.NETWORK_STATE_CONNECTED.value) {
        // /* w w  w. ja  v  a 2 s . c  o  m*/
        opsChangeRequest.addOps(SelectionKey.OP_WRITE);
        // ?selector
        weakup();
        return true;
    }

    return false;
}

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

@Override
public boolean notifyWrite(SocketChannel channel) {
    logger.debug("notifyWrite");
    if (channel == null) {
        return false;
    }/* w w  w  . j av  a  2  s.co m*/

    SocketChannelOPSChangeRequest request = opsChangeRequstMap.get(channel);
    if (request == null) {
        // Socket
        return false;
    }

    // 
    request.addOps(SelectionKey.OP_WRITE);
    // ?selector
    weakup();

    return true;
}