如何解析Netty(java)中的各种对象



我使用netty,我想从客户端发送各种对象到服务器,反之亦然。

我创建了相同的解码器和编码器类在客户端和服务器;

解码器:

public class UserInfoDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
...
list.add(new UserInfo(...))
 }
}

编码器:

public class UserInfoEncoder extends MessageToByteEncoder<UserInfo> {
        @Override
        protected void encode(ChannelHandlerContext ctx, UserInfo msg, ByteBuf out) {
...
 out.writeBytes(...);
}

这是我的服务器initChannel方法:

public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc()));
                            }
                            p.addLast(
                                  //  new ObjectEncoder(),
                                  //  new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                    new UserInfoDecoder(),
                                    new UserInfoEncoder(),
                                    new ObjectEchoServerHandler());
}

在服务器处理程序类

中有一个方法channelRead
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

...
    }

如何区分客户端发送的对象?例如,现在我只有"UserInfo"类,我可以在channelRead中转换"对象msg"到"UserInfo",但我想发送"UsersCar"对象,例如,如何通过发送的类型来区分对象?

就目前的实现而言,最简单的方法是在通过通道发送编码字节之前为其添加一个'magic byte'前缀。

public class UserInfoEncoder extends MessageToByteEncoder<UserInfo> {
    @Override
    protected void encode(ChannelHandlerContext ctx, UserInfo msg, ByteBuf out) {
    final int USER_BYTE = 0;
    out.writeBytes(USER_BYTE);
    out.writeBytes(msg.toBytes());
}

然后在服务器端,当消息被解码时,检查这个魔术字节并根据读取的值分配适当的解码器。例如:如果第一个未解码字节的值为0,则使用UserInfo解码器。如果第一个未解码字节的值为1,则使用UsersCar解码器。

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
   final ByteBuf message = (ByteBuf) msg;
   final byte magicByte= message.getByte(0);
   if(magicByte == 0){
      new UserInfoDecoder().decode(message);
   }else if {
    ....
   }
}

不是最简洁的解决方案,而是最简单的。

注意:这是假设你正在使用的处理程序正在扩展ChannelInboundHandlerAdapter

了解Netty编码/解码的一个好例子:http://shengwangi.blogspot.ie/2016/03/netty-tutorial-hello-world-example.html

最新更新