Christopher K. Christopher K. - 1 year ago 108
Java Question

Using Protocol Buffers and Netty 4.1.6

I have the following Server and Client initializers (both have extremely similar code where only

changes to
for the client, both representing their respective handlers).

public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("handler", sch);
ch.pipeline().addLast(new CommonClassHandler());
new ProtobufVarint32FrameDecoder());
new ProtobufDecoder(Server.MyMessage.getDefaultInstance()));
ch.pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());

I wish to use a binary format when sending commands/actions to the client or the server, therefore, I'm using Google's Protocol Buffers.

Here is where I create a
when dealing with the client's input:

while (channel.isOpen()) {
Client.MyMessage.Builder builder = Client.MyMessage.newBuilder();
String input = in.readLine(); // Save console input
builder.setKeyword(input); // Set the value of keyword to said input
channel.writeAndFlush(; // Send the build to the server

And finally here is the method automatically called when the server / client receive a message:

public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf bb = (ByteBuf)msg;
String order = bb.toString(Charset.defaultCharset());
System.out.println(order); // Displays received data

Server.MyMessage.Builder builder = Server.MyMessage.newBuilder();

1) When displaying the contents of my
it displays two unknown characters and a "\n" prior to my message; maybe I should handle my received data another way to have a normal display?

2) After displaying the received data, my server should send the answer "301" to my client, but to no use, as my client does not display anything (the method is not even called in the Client handler), is there an apparent reason?

Please excuse my questions, but there is very little documentation concerning the use of Protocol Buffers with Netty 4.1.6.

Answer Source

You are adding your handler at the start of your pipeline ch.pipeline().addLast("handler", sch);, but you should be putting it at the end of the pipeline, after your protobufDecoder.

Once you make that change you should start receiving MyMessage as your msg instead of a ByteBuf. I'm guessing that the unknown characters you are seeing right now are the frame lengths that get stripped by the frame decoder you have, but it won't run until after your handler the way you have things setup right now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download