Example usage for io.netty.channel.sctp.nio NioSctpChannel isOpen

List of usage examples for io.netty.channel.sctp.nio NioSctpChannel isOpen

Introduction

In this page you can find the example usage for io.netty.channel.sctp.nio NioSctpChannel isOpen.

Prototype

@Override
    public boolean isOpen() 

Source Link

Usage

From source file:com.mastfrog.scamper.Sender.java

License:Open Source License

/**
 * Send a message using the passed channel.
 *
 * @param channel The channel/*from www  . jav a2  s .c  o m*/
 * @param message A future which will be notified when the message is
 * flushed to the socket
 * @param sctpChannel The ordinal of the sctp channel
 * @return a future that will be notified when the message write is
 * completed
 * @throws IOException if something goes wrong
 */
@SuppressWarnings("unchecked")
public ChannelFuture send(Channel channel, final Message<?> message, int sctpChannel) throws IOException {
    Checks.notNull("channel", channel);
    Checks.notNull("message", message);
    Checks.nonNegative("sctpChannel", sctpChannel);
    ByteBufAllocator alloc = channel.alloc();
    ByteBuf outbound = alloc.buffer();
    if (message.body != null) {
        if (message.body instanceof ByteBuf) {
            outbound = (ByteBuf) message.body;
        } else {
            outbound = alloc.buffer();
            try (ByteBufOutputStream out = new ByteBufOutputStream(outbound)) {
                mapper.writeValue(message.body, out);
            }
        }
    }
    ByteBuf encodedBuffer = encoder.encode(message.type, outbound, channel);
    NioSctpChannel ch = (NioSctpChannel) channel;
    if (!ch.isOpen()) {
        return ch.newFailedFuture(new ClosedChannelException());
    }
    if (ch.association() == null) {
        return channel.newFailedFuture(new IOException("Association closed - client has disconnected"));
    }
    MessageInfo info = MessageInfo.createOutgoing(ch.association(), ch.remoteAddress(), sctpChannel);
    info.unordered(true);

    SctpMessage sctpMessage = new SctpMessage(info, encodedBuffer);
    logger.log(Level.FINE, "Send message to {0} type {1}",
            new Object[] { channel.remoteAddress(), message.type });
    ChannelFuture result = channel.writeAndFlush(sctpMessage);
    if (logger.isLoggable(Level.FINER)) {
        result.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.cause() != null) {
                    logger.log(Level.SEVERE, "Send to " + ch.remoteAddress() + " failed", future.cause());
                } else {
                    logger.log(Level.FINER, "Send completed to {0}", ch.remoteAddress());
                }
            }

        });
    }
    return result;
}