0%

mina自建codec filter

mina自带的codec filter已经很强大了,但是有的时候需要建立自己的codec filter。
在mina中调用session.wirte(object)可以发送一个对象,这个对象的类可以是用户自建的,只需要建立好相关的codec就可以正常发送。

这里新建一个简单的类表示时间:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 public class Time implements Serializable {
private int hours;
private int minutes;
private int seconds;
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
@Override
public String toString() {
return "Time now:"+hours+":"+minutes+":"+seconds;
}
}

然后是关于Time类的decoder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 public class TimeMessageDecoder implements MessageDecoder {
@Override
public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
if (in.remaining() < 1) {
return MessageDecoderResult.NEED_DATA;
}
// Return NOT_OK if not matches.
return MessageDecoderResult.OK;
}
@Override
public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
if (in.remaining() < 1) {
return MessageDecoderResult.NEED_DATA;
}
int hours = in.getInt();
int minutes = in.getInt();
int seconds = in.getInt();
Time time = new Time();
time.setHours(hours);
time.setMinutes(minutes);
time.setSeconds(seconds);
out.write(time);
return MessageDecoderResult.OK;
}
@Override
public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception {
// TODO Auto-generated method stub
}
}

以及encoder:

1
2
3
4
5
6
7
8
9
10
11
12
public class TimeMessageEncoder<T extends Time> implements MessageEncoder<T> {
@Override
public void encode(IoSession session, T message, ProtocolEncoderOutput out) throws Exception {
IoBuffer buffer = IoBuffer.allocate(100);
buffer.setAutoExpand(true);
buffer.putInt(message.getHours());
buffer.putInt(message.getMinutes());
buffer.putInt(message.getSeconds());
buffer.flip();
out.write(buffer);
}
}

CodecFactory:

1
2
3
4
5
6
public class TimeProtocolCodecFactory extends DemuxingProtocolCodecFactory {
public TimeProtocolCodecFactory() {
super.addMessageEncoder(Time.class, TimeMessageEncoder.class);
super.addMessageDecoder(TimeMessageDecoder.class);
}
}

在client中加入filterchain:

1
2
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TimeProtocolCodecFactory()));

在server中相应加入:

1
2
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TimeProtocolCodecFactory()));

这样就可以了,在handler中发数据直接session.write(object instace of Time);