问题描述
研究nanopb客户端服务器示例并尝试使用其他protobuf库。我的问题是: nanopb生成的protobuf是否与使用Google的protobuf-java以其他语言(如Java)生成的protobuf兼容?用nanopb编码的protobuf可以被Google protobuf库在Java中解码,反之亦然吗?我在C protobuf客户端和Java Protobuf服务器之间的套接字通信中遇到问题。 C客户端代码遵循nanopb network_server示例,客户端服务器共享相同的原型消息。 C客户端和C服务器运行正常,类似地,Java客户端和Java Server也运行良好。但是,当C客户端连接到Netty TCP服务器时,它不会显示任何输出。
message Sample {
optional string value = 1;
}
选项已定义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,&message))
{
printf("Encoding Failed: %s\n",PB_GET_ERROR(&output));
}
Java TCP Server(基于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客户端的客户端发送数据。有什么建议为什么我的代码会失败吗?谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)