【问题标题】:Multiple messages contained in one netty buffer issue一个 netty 缓冲区问题中包含多条消息
【发布时间】:2012-10-09 08:58:27
【问题描述】:

我已经使用 netty 网络库为游戏客户端构建了一个登录服务器。
该游戏客户端喜欢在单个缓冲区中发送多个数据包,这会带来问题;这个问题是在 netty 解码类中,它只能返回一条消息。

那么我不可能将多个数据包读入多个消息并在一个解码方法调用中返回它们。

我的问题是:我应该如何最好地在一个 DecoderClass.decode() 方法调用中接收多个数据包?由于只能返回一个对象,我很困惑。

我的初步解码类如下:

protected Object decode(ChannelHandlerContext ctx, Channel c, ChannelBuffer buf,           
    VoidEnum state) throws Exception {
    short length = -1;
    short opcode = -1;
    short security = -1;

    while(buf.readableBytes() != 0 ){
        length = buf.readShort();
        opcode = buf.readShort();
        security = buf.readShort();
    }

    System.out.println("---------------------------------------");
    System.out.println("receivedLength: " + length);
    System.out.println("receivedOPCode: " + opcode);
    System.out.println("receivedSecurity: " + security);
    System.out.println("---------------------------------------");

    MessageCodec<?> codec = CodecLookupService.find(opcode);
    if (codec == null) {
        throw new IOException("Unknown op code: " + opcode + " (previous opcode: " + previousOpcode + ").");
    }


    previousOpcode = opcode;


    return codec.decode(buf);

我的完整 github 存储库在这里:https://github.com/desmin88/LoginServer

我希望我提供了足够的信息,以便有人能够充分理解我的问题

谢谢,

比利

【问题讨论】:

    标签: java netty decode channel


    【解决方案1】:

    您需要使用FrameDecoder 将接收到的数据拆分为多个“帧”以传递给您的解码器。 FrameDecoder 的 API 参考中有一些 example code

    与其发表更多评论,不如这样做:

    1. 实现您自己的FrameDecoder 或使用现有的之一。假设您实现了自己的MyGameFrameDecoder。如果您自己编写,我建议您查看ReplayingDecoder(这很糟糕)。
    2. MyGameFrameDecoder 添加到服务器端的ChannelPipeline 以及您现有的解码器(DecoderClass)。

    看起来像这样:

    /* ... stuff ... */
    pipeline.addLast("framer", new MyGameFrameDecoder());
    pipeline.addLast("decoder", new DecoderClass());
    /* ... more stuff ... */
    

    然后传入的数据将通过FrameDecoder 并将流分解为“帧”,然后将其发送到您的解码器,该解码器可以将数据转换为您可以操作的对象。

    【讨论】:

    • 所以我写了一个 FrameDecoder,它将接收到的数据分成帧,然后传递到哪里?
    • 您的DecoderClass。您可以编写自己的FrameDecoder(或使用现有的之一)并将其添加到您的频道管道中。
    猜你喜欢
    • 2011-07-31
    • 2015-06-02
    • 2020-02-13
    • 2012-03-27
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多