探索 nanopb 客户端服务器示例并尝试使用其他 protobuf 库。我的问题是: nanopb 生成的 protobuf 是否与使用 google 的 protobuf-java 以其他语言(如 java)生成的 protobuf 兼容?用 nanopb 编码的 protobuf 可以由 java 中的 google protobuf 库解码,反之亦然?我在 C protobuf 客户端和 Java Protobuf 服务器之间的套接字通信中遇到了问题。C 客户端代码遵循 nanopb network_server 示例,客户端服务器共享相同的原始消息。C 客户端和 C 服务器运行良好,Java 客户端和 Java 服务器也运行良好。但是,当 C 客户端连接到 Netty TCP 服务器时,它没有显示任何输出。
message Sample {
optional string value = 1;
}
options 定义了 max_size。
C 客户端代码片段:
Sample message = Sample_init_default;
pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
strcpy(message.value,"device1");
status = pb_encode(&stream, Sample_fields, &message);
message_length = stream.bytes_written;
if (!status)
{
printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
return 1;
}
pb_ostream_t output = pb_ostream_from_socket(sockfd);
if (!pb_encode_delimited(&output, Sample_fields, &message))
{
printf("Encoding failed: %s\n", PB_GET_ERROR(&output));
}
Java TCP 服务器(基于 Netty)片段:
// main calls run method
public void run() {
EventLoopGroup ServerGroup = new NioEventLoopGroup();
try{
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(ServerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ServerInitializer());
ChannelFuture future = bootstrap.bind(1234).sync();
future.channel().closeFuture().sync();
} catch(Exception ex) {
System.out.println(ex);
}
finally{
System.out.println("Logging Off");
ServerGroup.shutdownGracefully();
}
}
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
try {
ChannelPipeline p = ch.pipeline();
//add decoders and encoders
p.addLast(new ProtobufVarint32FrameDecoder());
p.addLast(new ProtobufDecoder(SampleProtos.Sample.getDefaultInstance()));
p.addLast(new ProtobufVarint32LengthFieldPrepender());
p.addLast(new ProtobufEncoder());
//handler for business logic
p.addLast(new ServerHandler());
} catch (Exception ex) {
System.out.println(ex);
}
}
}
public class ServerHandler extends ChannelInboundHandlerAdapter {
.........
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Channel Read...");
try {
SampleProtos.Sample sample = (SampleProtos.Sample)msg;
System.out.println("Value Read: " + sample.getValue());
sample = sample.toBuilder().setValue("Server Response").build();
ctx.writeAndFlush(sample);
} catch (Exception ex){
System.out.println(ex);
}
}
}
C 客户端的服务器输出为空白,但显示 Java Netty 客户端的客户端发送数据。任何建议为什么我的代码失败?感谢期待。