Answer the question
In order to leave comments, you need to log in
How to properly cast deserialized protobuf data to one type?
Good evening. I will try to describe the problem in detail, since I asked a question on stackoverflow and did not receive an answer.
So. We have a java server using the Netty.io framework .
The server receives packets from the client in C# in the form:
[2byte length][1byte type][Xbyte protobuf data]
The server in its pipeline pumps out the required frame based on the length bytes. And as a result, 1 frame arrives in the handler: [1byte type][Xbyte protobuf data] this is 1 packet from the client that needs to be passed to the processing logic without delaying the Netty streams.
For
greater clarity, I will give the code described above .
private static void start(){
LOG.info("Starting netty");
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(3);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(Config.PORT))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("Register",new RegisterHandler());
ch.pipeline().addLast("FrameDecoder",new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN,27,0,2,0,2,true));
ch.pipeline().addLast(new ByteToPackageDecoder());
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} catch (Exception ex) {
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Logic.listMSG.add(in);
Logic.getLogin();
int bits32 = (int) in.getByte(0) & 0xff; //Читаем правильно 1 байт(убираем отрицательные числа)
LOG.info("Bytes to frame:" + in.readableBytes() + "READ 1 byte: " + bits32);
byte[] buf = new byte[in.readableBytes() - 1];
in.getBytes(1, buf);
Package p = new Package(1, buf, ctx);
switch (bits32) {
case 1:
Login1PackageOuterClass.Login1Package Login1Package = Login1PackageOuterClass.Login1Package.parseFrom(buf);
LOG.debug("Read message : " + Login1Package.getLogin());
}
}
Login1PackageOuterClass.Login1Package Login1Package = Login1PackageOuterClass.Login1Package.parseFrom(buf);
Answer the question
In order to leave comments, you need to log in
The problem is sucked from the finger. Protobuf decodes quickly. This is what it was created for.
Don't use switch/case constructs. In this case, an array of dispatchers suggests itself, each of which decodes the protobuf and sends the request further, each to its own handler. You can do this in different ways. If you want, get in line. But it's easier to make an Executor and process it in a certain number of threads.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question