【发布时间】:2016-11-17 22:46:58
【问题描述】:
我有以下服务器和客户端初始化程序(两者都有非常相似的代码,其中只有客户端的 sch 更改为 cch,都代表它们各自的处理程序)。
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("handler", sch);
ch.pipeline().addLast(new CommonClassHandler());
ch.pipeline().addLast("frameDecoder",
new ProtobufVarint32FrameDecoder());
ch.pipeline().addLast("protobufDecoder",
new ProtobufDecoder(Server.MyMessage.getDefaultInstance()));
ch.pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
ch.pipeline().addLast("protobufEncoder", new ProtobufEncoder());
}
我希望在向客户端或服务器发送命令/操作时使用二进制格式,因此,我使用的是 Google 的Protocol Buffers。
这是我在处理客户输入时创建builder 的地方:
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(builder.build()); // Send the build to the server
}
最后是服务器/客户端收到消息时自动调用的方法:
@Override
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();
builder.setKeyword("301");
ctx.writeAndFlush(builder.build());
}
1) 当显示我的ByteBuf 的内容时,它会在我的消息前显示两个未知字符和一个“\n”;也许我应该以另一种方式处理收到的数据以正常显示?
2) 显示接收到的数据后,我的服务器应该将答案“301”发送给我的客户端,但没有用,因为我的客户端不显示任何内容(甚至没有调用该方法在客户端处理程序中),是否有明显的原因?
请原谅我的问题,但是关于在 Netty 4.1.6 中使用 Protocol Buffers 的文档很少。
【问题讨论】:
标签: java netty protocol-buffers