Search code examples
javanettynio

What Channel handlers to use to send custom Java objects via Netty 4?


So, I am just getting started with Netty 4, and I am trying to pass a message from a client to the server and back.

I had initially tried sending only Strings and my server's initChannel() method was defined as below:

public class Initializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
        ch.pipeline().addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
        ch.pipeline().addLast("chatHandler", new Handler());
    }
}

The Handler class contains the channelRead() etc. event-handlers.

Now, I want to extend this so as to send custom objects, instead of Strings. In that case, what should be the best way to go about it? What encoders and decoders in netty can I use to extend them to achieve my purpose? Ideally, what I should be looking for are ChannelHandlers that can convert from custom object type to ByteBuf and vice-versa, right? Or am I missing something?

Thanks in advance.


Solution

  • You should use your own decoder/encoder implementation for that. Alternative you could use either the protobuf support or the codec that uses java serialization / jboss marshalling for that.