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.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

private void dispatch() throws IOException {
    logger.debug("try dispatch");
    SelectionKey key = null;//from  w  ww .  j a  v a 2  s .c om
    for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) {
        key = request.getChannel().keyFor(selector);
        if (key != null) {
            // 
            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:com.buaa.cfs.net.SocketIOWithTimeout.java

private static String timeoutExceptionString(SelectableChannel channel, long timeout, int ops) {

    String waitingFor;/*from  w w w . jav a2 s . c o  m*/
    switch (ops) {

    case SelectionKey.OP_READ:
        waitingFor = "read";
        break;

    case SelectionKey.OP_WRITE:
        waitingFor = "write";
        break;

    case SelectionKey.OP_CONNECT:
        waitingFor = "connect";
        break;

    default:
        waitingFor = "" + ops;
    }

    return timeout + " millis timeout while " + "waiting for channel to be ready for " + waitingFor + ". ch : "
            + channel;
}

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

private void onWritable() {
    try {//from   w  ww  .  j a  va  2 s  .  c om
        writeKey.interestOps(writeKey.interestOps() & ~SelectionKey.OP_WRITE);

        boolean writeComplete = false;
        while (true) {
            Object[] objs = (Object[]) writeQueue.peek();
            if (objs == null) {
                writeComplete = true;
                break;
            }
            Message message = writeToChannel(writeChannel, objs[0]);
            if (message != null) { //write complete
                writeQueue.pop();
                dispatchMessageSent(message);
                WriteLock writeLock = (WriteLock) objs[1];
                if (writeLock != null) {
                    writeLock.setSuccess(true);
                    synchronized (writeLock) {
                        writeLock.notify();
                    }
                }
            } else { //not write complete, but write buffer is full
                break;
            }
        }

        if (writeComplete)
            dispatchSessionIdle();
        else
            ((EventGeneratorSpi) getEventGenerator()).register(this, Constants.EV_ENABLE_WRITE); //not write complete keep listening OP_WRITE
    } catch (CancelledKeyException cke) {
        close();
    } catch (ClosedChannelException cce) {
        close();
    } catch (IOException ioe) {
        dispatchException(ioe);
        close();
    } catch (Exception e) {
        dispatchException(e);
    }
}

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

@Override
public void consumeData(final IOSession iosession, final ClientState state)
        throws IOException, SMTPProtocolException {
    Args.notNull(iosession, "IO session");
    Args.notNull(state, "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 AUTH_RESPONSE_READY:
            AuthMode mode = (AuthMode) iosession.getAttribute(AUTH_TYPE);

            if (reply.getCode() == SMTPCodes.START_AUTH_INPUT) {
                if (mode == AuthMode.PLAIN) {
                    this.codecState = CodecState.AUTH_PLAIN_INPUT_READY;
                } else if (mode == AuthMode.LOGIN) {
                    this.codecState = CodecState.AUTH_LOGIN_USERNAME_INPUT_READY;
                }/*www. java2 s  . c o  m*/
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
            }
            break;

        case AUTH_PLAIN_INPUT_RESPONSE_EXPECTED:

            if (reply.getCode() == SMTPCodes.AUTH_OK) {
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);

            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
            }
            break;

        case AUTH_LOGIN_USERNAME_INPUT_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.START_AUTH_INPUT) {
                this.codecState = CodecState.AUTH_LOGIN_PASSWORD_INPUT_READY;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                throw new SMTPProtocolException("Unexpected reply:" + reply);
            }

            break;

        case AUTH_LOGIN_PASSWORD_INPUT_RESPONSE_EXPECTED:
            if (reply.getCode() == SMTPCodes.AUTH_OK) {
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);
                iosession.setEvent(SelectionKey.OP_WRITE);
            } else {
                // TODO: should we set the failure here ?
                //       At the moment we just process as maybe its possible to send
                //       the mail even without auth
                this.codecState = CodecState.COMPLETED;
                state.setReply(reply);

            }
            break;

        default:
            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                state.setReply(reply);
                this.codecState = CodecState.COMPLETED;
            } else {
                throw new SMTPProtocolException("Unexpected reply:" + reply);
            }
        }
    } else {
        if (bytesRead == -1 && !state.isTerminated()) {
            throw new UnexpectedEndOfStreamException();
        }
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

private void doConnect(SelectionKey key) {

    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final SocketChannel socketChannel = (SocketChannel) key.channel();
    try {/*from  w  w  w .  j  a v a  2  s  .  c o  m*/
        while (!socketChannel.finishConnect()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                LOG.error(e1);
            }
        }

        final SelectionKey channelKey = socketChannel.register(selector,
                SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        outgoingConnection.setSelectionKey(channelKey);
        channelKey.attach(outgoingConnection);

    } catch (IOException ioe) {
        outgoingConnection.reportConnectionProblem(ioe);
    }
}

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

public void notifySend(SocketChannel socketChannel) {
    try {/*w  w  w .  j a  v  a 2 s  .c  o  m*/
        // we synchronize this to make sure we register the key before the selector gets back to sleep again.
        if (socketChannel.isOpen() && selector.isOpen()) {
            selector.wakeup();
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

        }

    } catch (ClosedChannelException e) {
        //Disconnect detected
    } catch (CancelledKeyException e) {

    } catch (Exception e) {

        LoggerFactory.getLogger(this.getClass()).error("Exception", e);

    }
}

From source file:com.facebook.infrastructure.net.TcpConnection.java

public void stream(File file, long startPosition, long endPosition) throws IOException {
    if (!bStream_)
        throw new IllegalStateException("Cannot stream since we are not set up to stream data.");

    lock_.lock();/*from   w w w . j  a va 2 s.co  m*/
    try {
        /* transfer 64MB in each attempt */
        int limit = 64 * 1024 * 1024;
        long total = endPosition - startPosition;
        /* keeps track of total number of bytes transferred */
        long bytesWritten = 0L;
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel fc = raf.getChannel();

        /* 
         * If the connection is not yet established then wait for
         * the timeout period of 2 seconds. Attempt to reconnect 3 times and then 
         * bail with an IOException.
        */
        long waitTime = 2;
        int retry = 0;
        while (!connected_.get()) {
            if (retry == 3)
                throw new IOException("Unable to connect to " + remoteEp_ + " after " + retry + " attempts.");
            waitToContinueStreaming(waitTime, TimeUnit.SECONDS);
            ++retry;
        }

        while (bytesWritten < total) {
            if (startPosition == 0) {
                ByteBuffer buffer = MessagingService.constructStreamHeader(false, true);
                socketChannel_.write(buffer);
                handleIncompleteWrite(buffer);
            }

            /* returns the number of bytes transferred from file to the socket */
            long bytesTransferred = fc.transferTo(startPosition, limit, socketChannel_);
            logger_.trace("Bytes transferred " + bytesTransferred);
            bytesWritten += bytesTransferred;
            startPosition += bytesTransferred;
            /*
             * If the number of bytes transferred is less than intended 
             * then we need to wait till socket becomes writeable again. 
            */
            if (bytesTransferred < limit && bytesWritten != total) {
                if ((key_.interestOps() & SelectionKey.OP_WRITE) == 0) {
                    SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
                }
                waitToContinueStreaming();
            }
        }
    } finally {
        lock_.unlock();
    }
}

From source file:com.facebook.infrastructure.net.TcpConnection.java

private void handleIncompleteWrite(ByteBuffer buffer) {
    if (buffer.remaining() > 0) {
        pendingWrites_.add(buffer);/*from   w  w w.  jav  a2  s  .  co  m*/
        if ((key_.interestOps() & SelectionKey.OP_WRITE) == 0) {
            SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
        }
        waitToContinueStreaming();
    }
}

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

/**
 * ?, ?, ?, ??/*from ww w  . ja v a2s . co  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.ok2c.lightmtp.impl.protocol.ClientSession.java

private void updateSession() throws IOException, SMTPProtocolException {
    if (this.currentCodec.isCompleted()) {

        SMTPReply reply = this.sessionState.getReply();
        if (reply != null) {
            if (this.log.isDebugEnabled()) {
                this.log.debug(this.state + " codec completed with reply: " + reply);
            }/*from   ww  w.  j  a  v a  2 s .  c o m*/

            switch (this.state) {
            case HELO:
                if (reply.getCode() != SMTPCodes.OK) {
                    throw new ServiceRefusedException(reply);
                }
                break;
            case MAIL:
                if (reply.getCode() != SMTPCodes.START_MAIL_INPUT) {
                    if (this.sessionState.getRequest() == null) {
                        break;
                    }
                    signalDeliveryFailure();
                }
                break;
            case DATA:
                if (reply.getCode() == SMTPCodes.OK) {
                    signalDeliverySuccess();
                } else {
                    signalDeliveryFailure();
                }
                break;
            }

            if (reply.getCode() == SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE) {
                this.sessionState.terminated();
                this.iosession.close();
            }
        }
    }

    String nextCodec = this.currentCodec.next(this.codecs, this.sessionState);
    if (nextCodec != null) {
        this.state = ProtocolState.valueOf(nextCodec);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Next codec: " + this.state);
        }
        this.currentCodec = this.codecs.getCodec(nextCodec);
        this.currentCodec.reset(this.iosession, this.sessionState);

        if (this.state == ProtocolState.MAIL) {
            signalDeliveryReady();
        }
    }

    ProtocolState token = (ProtocolState) this.iosession.getAttribute(ProtocolState.ATTRIB);
    if (token != null && token.equals(ProtocolState.QUIT)) {
        this.log.debug("Session termination requested");
        this.sessionState.terminated();
        this.iosession.setEvent(SelectionKey.OP_WRITE);
    }
}