2012-10-18 55 views
4

我爲使用netty網絡庫的遊戲客戶端構建了一個登錄服務器。
這個遊戲客戶端喜歡在單個緩衝區中發送多個數據包,這會造成問題;這個問題是在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

我希望我能提供足夠的信息,以便有人能充分理解我的問題

謝謝,

比利

回答

4

您需要使用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,打破了流進然後將發送到您的解碼器「幀」,它可以只處理將數據轉換爲您可以操作的對象。

+0

因此,我寫了一個FrameDecoder,當我傳遞到哪裏時,將接收到的數據拆分爲幀? –

+0

您的'DecoderClass'。你可以編寫你自己的'FrameDecoder'(或者使用現有的FrameDecoder),並將它添加到你的頻道管道中。 –