Netty doesn’t write

Netty is asynchronous, meaning that it won’t throw exceptions when a write failed. Instead of throwing exceptions, it returns a Future<?> that will be updated when the request is done. Make sure to log any exceptions coming from this as your first debugging steps:

channel.writeAndFlush(...).addListener(new GenericFutureListener<Future<Object>>() {
    @Override
    public void operationComplete(Future<Object> future) {
        // TODO: Use proper logger in production here
        if (future.isSuccess()) {
            System.out.println("Data written succesfully");
        } else {
            System.out.println("Data failed to write:");
            future.cause().printStackTrace();
        }
    }
});

Or more simply:

channel.writeAndFlush(...).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);

After you get the root cause of the exception, there could be multiple problems:

java.lang.UnsupportedOperationException:
unsupported message type: <type> (expected: ...)

Notice: This also throws when using an ObjectEncoder, but your object does not implements Serializable

A default Netty channel can only send ByteBufs and FileRegions. You need to convert your objects to these types either by adding more handlers to the pipeline, or converting them manually to ByteBufs.

A ByteBuf is the Netty variant of a byte array, but has the potential for performance because it can be stored in the direct memory space.

The following handlers are commonly used:

To convert a String use a StringEncoder
To convert a Serializable use a ObjectEncoder (warning, not compatible with normal Java object streams)
To convert a byte[] use a ByteArrayEncoder

Notice: Since TCP is a stream based protocol, you usually want some form of packet sizes attached, since you may not receive exact packets that you write. See Dealing with a Stream-based Transport in the Netty wiki for more information.

Leave a Comment