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.l2jfree.network.mmocore.ReadWriteThread.java

@Override
protected void handle(SelectionKey key) {
    System.out.println("ReadWriteThread.handle() " + describeInterestOps(key.interestOps()) + ", ready: "
            + describeInterestOps(key.readyOps()));
    switch (key.readyOps()) {
    case SelectionKey.OP_CONNECT:
        finishConnection(key);//from  w ww . j  a  v a2s .  c o  m
        break;
    case SelectionKey.OP_READ:
        readPacket(key);
        break;
    case SelectionKey.OP_WRITE:
        writePacket(key);
        break;
    case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
        writePacket(key);
        // key might have been invalidated on writePacket
        if (key.isValid())
            readPacket(key);
        break;
    default:
        System.err.println("Unknown readyOps: " + key.readyOps() + " for " + key.attachment());
        break;
    }
}

From source file:com.tera.common.network.nio.MMOConnection.java

final void disableWriteInterest() {
    try {//  w ww  . j  a v a  2  s  . co  m
        getSelectionKey().interestOps(getSelectionKey().interestOps() & ~SelectionKey.OP_WRITE);
    } catch (CancelledKeyException e) {
        // ignore
    }
}

From source file:com.ok2c.lightmtp.impl.protocol.ReceiveDataCodec.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.pendingDelivery != null) {
            if (this.pendingDelivery.isDone()) {
                deliveryCompleted(sessionState);
                cleanUp();/*from  ww w .  ja va 2s  .  c om*/
            }
            while (!this.pendingReplies.isEmpty()) {
                this.writer.write(this.pendingReplies.removeFirst(), buf);
            }
        }

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

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

private void updateSession() throws IOException, SMTPProtocolException {
    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);
        }/* www  . ja va2  s .c  o  m*/
        this.currentCodec = this.codecs.getCodec(nextCodec);
        this.currentCodec.reset(this.iosession, this.sessionState);

        if (this.log.isDebugEnabled()) {
            switch (this.state) {
            case DATA:
                String messageId = this.sessionState.getMessageId();
                String sender = this.sessionState.getSender();
                List<String> recipients = this.sessionState.getRecipients();
                this.log.debug("Incoming message " + messageId + " [" + sender + "] -> " + recipients);
                break;
            }
        }
    }
    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);
    }
}

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

public void write(Message message) throws IOException {
    byte[] data = serializer_.serialize(message);
    if (data.length <= 0) {
        return;/*  ww  w . ja v  a 2 s.  c  om*/
    }
    boolean listening = !message.getFrom().equals(EndPoint.randomLocalEndPoint_);
    ByteBuffer buffer = MessagingService.packIt(data, false, false, listening);
    synchronized (this) {
        if (!pendingWrites_.isEmpty() || !connected_.get()) {
            pendingWrites_.add(buffer);
            return;
        }

        logger_.trace("Sending packet of size " + data.length);
        socketChannel_.write(buffer);

        if (buffer.remaining() > 0) {
            pendingWrites_.add(buffer);
            if ((key_.interestOps() & SelectionKey.OP_WRITE) == 0) {
                SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
            }
        }
    }
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteFailed() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String message = "hi\n";
    when(socket.write(any(ByteBuffer.class))).thenThrow(new IOException("write failed"));
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();/*w w  w  .java  2  s.  co m*/
    List<String> callbackInvoked = new ArrayList<>();
    List<Exception> exceptionHandlerInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = exceptionHandlerInvoked::add;
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(0, messageStream.size());
    Assert.assertEquals(0, callbackInvoked.size());
    Assert.assertEquals(1, exceptionHandlerInvoked.size());
}

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

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

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    switch (this.codecState) {
    case CONTENT_READY:
        int bytesRead = 0;
        while (buf.length() < LIMIT) {
            if (!this.contentBuf.hasData()) {
                bytesRead = this.contentBuf.fill(this.contentChannel);
            }//w  w w. j av a2s. c o  m

            boolean lineComplete = this.contentBuf.readLine(this.lineBuf, bytesRead == -1);
            if (this.maxLineLen > 0 && (this.lineBuf.length() > this.maxLineLen
                    || (!lineComplete && this.contentBuf.length() > this.maxLineLen))) {
                throw new SMTPProtocolException("Maximum line length limit exceeded");
            }
            if (lineComplete) {
                if (this.lineBuf.length() > 0 && this.lineBuf.charAt(0) == '.') {
                    buf.write(PERIOD);
                }
                buf.writeLine(this.lineBuf);
                this.lineBuf.clear();
            } else {
                bytesRead = this.contentBuf.fill(this.contentChannel);
            }
            if (bytesRead == -1 && !this.contentBuf.hasData()) {

                this.lineBuf.clear();
                this.lineBuf.append('.');
                buf.writeLine(this.lineBuf);
                this.lineBuf.clear();

                this.content.reset();
                this.contentSent = true;
                this.codecState = CodecState.CONTENT_RESPONSE_EXPECTED;
                break;
            }
            if (bytesRead == 0 && !lineComplete) {
                break;
            }
        }
    }

    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData() && this.contentSent) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}

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

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

    SessionOutputBuffer buf = this.iobuffers.getOutbuf();

    switch (this.codecState) {
    case AUTH_READY:
        AuthMode mode = null;//from   ww w .  ja v  a 2s.com
        for (final String extension : state.getExtensions()) {
            if (extension.startsWith(ProtocolState.AUTH.name())) {
                String types = extension.substring(ProtocolState.AUTH.name().length() + 1);
                mode = getAuthMode(types);
                if (mode != null) {
                    break;
                }
            }
        }
        if (mode == null) {
            // TODO: Maybe we should just skip auth then and call the next codec in the chain
            throw new SMTPProtocolException("Unsupported AUTH types");
        } else {
            iosession.setAttribute(AUTH_TYPE, mode);
        }

        SMTPCommand auth = new SMTPCommand("AUTH", mode.name());
        this.writer.write(auth, buf);
        this.codecState = CodecState.AUTH_RESPONSE_READY;
        break;

    case AUTH_PLAIN_INPUT_READY:
        byte[] authdata = Base64.encodeBase64(("\0" + username + "\0" + password).getBytes(AUTH_CHARSET));
        lineBuf.append(authdata, 0, authdata.length);
        this.codecState = CodecState.AUTH_PLAIN_INPUT_RESPONSE_EXPECTED;
        break;

    case AUTH_LOGIN_USERNAME_INPUT_READY:
        byte[] authUserData = Base64.encodeBase64(username.getBytes(AUTH_CHARSET));
        lineBuf.append(authUserData, 0, authUserData.length);

        this.codecState = CodecState.AUTH_LOGIN_USERNAME_INPUT_RESPONSE_EXPECTED;
        break;

    case AUTH_LOGIN_PASSWORD_INPUT_READY:
        byte[] authPassData = Base64.encodeBase64(password.getBytes(AUTH_CHARSET));
        lineBuf.append(authPassData, 0, authPassData.length);

        this.codecState = CodecState.AUTH_LOGIN_PASSWORD_INPUT_RESPONSE_EXPECTED;
        break;
    }

    if (!lineBuf.isEmpty()) {
        buf.writeLine(lineBuf);
        lineBuf.clear();
    }
    if (buf.hasData()) {
        buf.flush(iosession.channel());
    }
    if (!buf.hasData()) {
        iosession.clearEvent(SelectionKey.OP_WRITE);
    }
}

From source file:idgs.client.TcpClient.java

public void write() throws IOException {
    channel.register(selector, SelectionKey.OP_WRITE);
    select();
}

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

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

    SessionInputBuffer buf = this.iobuffers.getInbuf();

    synchronized (sessionState) {
        for (;;) {
            int bytesRead = buf.fill(iosession.channel());
            try {
                SMTPCommand command = this.parser.parse(buf, bytesRead == -1);
                if (command == null) {
                    if (bytesRead == -1 && !sessionState.isTerminated() && this.pendingActions.isEmpty()) {
                        throw new UnexpectedEndOfStreamException();
                    } else {
                        break;
                    }//from  w  ww  .j av a  2s.c om
                }
                Action<ServerState> action = this.commandHandler.handle(command);
                this.pendingActions.add(action);
            } catch (SMTPErrorException ex) {
                SMTPReply reply = new SMTPReply(ex.getCode(), ex.getEnhancedCode(), ex.getMessage());
                this.pendingActions.add(new SimpleAction(reply));
            } catch (SMTPProtocolException ex) {
                SMTPReply reply = new SMTPReply(SMTPCodes.ERR_PERM_SYNTAX_ERR_COMMAND, new SMTPCode(5, 3, 0),
                        ex.getMessage());
                this.pendingActions.add(new SimpleAction(reply));
            }
        }

        if (!this.pendingActions.isEmpty()) {
            iosession.setEvent(SelectionKey.OP_WRITE);
        }
    }
}