我已经使用 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
我希望我提供了足够的信息,以便有人能够充分理解我的问题
谢谢,
比利
最佳答案
您需要使用 FrameDecoder
将接收到的数据拆分为多个“帧”以传递给您的解码器。有一些 example code在 FrameDecoder
的 API 引用中。
与其评论更多,不如这样做:
- 实现您自己的
FrameDecoder
或使用现有的之一。假设您实现了自己的MyGameFrameDecoder
。如果您自己编写,我建议您查看ReplayingDecoder
(这很糟糕)。 - 将
MyGameFrameDecoder
添加到服务器端的ChannelPipeline
以及您现有的解码器 (DecoderClass
)。
看起来像这样:
/* ... stuff ... */
pipeline.addLast("framer", new MyGameFrameDecoder());
pipeline.addLast("decoder", new DecoderClass());
/* ... more stuff ... */
然后传入的数据将通过 FrameDecoder
并将流分解为“帧”,然后将其发送到您的解码器中,解码器可以处理将数据转换为您可以操作的对象上。
关于java - 一个 netty 缓冲区问题中包含多条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12962490/