Tim's Blog about XMPP Jabber, 同时欢迎访问我的另一独立blog: http://timyang.net/
查看文章 |
MINA ProtocolDecoder doDecode 调错
2008-10-21 18:52
Mina是一种Java中使用广泛的网络框架,Mina写一个Hello world可能5分钟就可以了(参看 Mina测试程序)。 其中最复杂的部分可能就是Decode解码。其作用是将网络的二进制数据流转换成业务逻辑的对象。我前面那个例子为了简化目的,codec用的是Mina中现成的 TextLineDecoder,有些朋友一字不改拿去之后说程序有问题。没错,肯定有问题,因为TextLineDecoder每次读一行, 如果服务器一直不给换行就一直等在那了。那怎么改啊,自己想去吧。 doDecode的返回参数是不太直观的,这两天碰到问题了。我们有个服务器之间通讯的程序,压力测试时候反应很慢,现象有:
* Implement this method to consume the specified cumulative buffer and * decode its content into message(s). * * @param in the cumulative buffer * @return true if and only if there's more to decode in the buffer * and you want to have doDecode method invoked again. * Return false if remaining data is not enough to decode, * then this method will be invoked again when more data is cumulated. * @throws Exception if cannot decode in. */ protected abstract boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception; 按上面的意思我是这样实现的,核心片断: int pos = in.position();问题就在 return !in.hasRemaining(); 上面。这里是应该返回true的。
如果你对 ProtocolDecoder 感兴趣,我建议新手去看 ObjectSerializationDecoder / ObjectSerializationEncoder 的代码,特别简洁。不要看 TextLineDecoder, 无关细节太多。 |
最近读者: