舉個例子:
public class Myecode implements ProtocolEncoder {
// 過濾器會自動跳入此方法
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
List<String> db = (List<String>)message;//message代表session.write(Object obj)的obj,可以是自定義對象,後續文章會有講解
byte[] data = //回寫到客戶端的流,一般都是message提供的流對象;
ByteBuffer buffer = ByteBuffer.allocate(data.length);//MINA提供的工具ByteBuffer,創建一個長度爲data.length的ByteBuffer
try {
buffer.putInt(data.length);//向流中寫入一個int
} catch (Exception ex) {
buffer.putInt(0);
}
buffer.put(data);//流中寫入byte數組
buffer.flip();//有點壓棧的意思,還不是很清楚
out.write(buffer);//向客戶端寫入數據,並進入下一個過濾,沒有過濾的話就響應到客戶端了。
}
public void dispose(IoSession session) throws Exception {
}
}