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 String
s 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 String
s. 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 ChannelHandler
s that can convert from custom object type to ByteBuf
and vice-versa, right? Or am I missing something?
Thanks in advance.
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.