使用mina的TextLineDecoder,可以指定接收数据的结束符号,但如果没有指定结束符,就默认会去匹配'/n'或者'/r'结束符
如果从服务端返回的数据没有包含这些结束符,客户端就会等待。
为了不让客户端等待下去,可以增加一个TextLineDecoder子类,如下:
public class ClientTextLineDecoder extends TextLineDecoder {
@Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
/*--------在当前buffer后面追加一个'/n' -------*/
in.setAutoExpand(true);//设置自动扩展
in.position(in.limit());
in.put((byte)'/n');
in.position(0);
super.decode(session, in, out);
}
}
我们只要在调用父类的decode方法之前在buffer后面追加一个'/n'结束符,就可以解决问题。
下面是buffer相关的知识:
The abstract Buffer class forms the foundation of the java.nio package's buffer support. Buffer works like an in-memory RandomAccessFile for reading and writing primitive data types. Like a RandomAccessFile , with Buffer the next operation you perform (read/write) happens at your position. Performing either operation changes that position, so doing a read after a write doesn't read what was just written, but what is after what was just written. Buffer offers four indicators for access to the linear structure (from highest value to lowest):
-
capacity(): Indicates the buffer's size -
limit(): Tells you how many bytes you've stuffed into the buffer so far, or lets you change that limit with:limit(int newLimit): -
position(): Tells you the current location to perform the next read/write operation -
mark(): Lets you remember a position for later resetting withreset()
具体可以参考:http://www.ibm.com/developerworks/java/library/j-mer03253.html
本文介绍了一个解决Mina框架中TextLineDecoder在特定情况下导致客户端等待的方法。通过继承TextLineDecoder并覆盖decode方法,在接收的数据末尾强制添加'/n'来确保消息能够被正确解析。
502

被折叠的 条评论
为什么被折叠?



