MessageDecoder.java
2.09 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.bsth.socket.codec;
import com.bsth.socket.protocol.Message;
import com.bsth.service.UpProtocolDataService;
import com.bsth.util.AppProperties;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
/**
* @author Hill
*/
public class MessageDecoder extends CumulativeProtocolDecoder {
private final static Logger log = LoggerFactory.getLogger(MessageDecoder.class);
@Override
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
// TODO Auto-generated method stub
while (in.remaining() > 1) {
in.mark();
byte start1 = in.get();
if (start1 == 0x23) {
byte start2 = in.get();
if (start2 == 0x23) {
if (in.remaining() > 21) {
byte[] bytes1 = new byte[22];
in.get(bytes1);
byte lenHigh = bytes1[20], lenLow = bytes1[21];
int len = ((lenHigh & 0xff) << 8) + (lenLow & 0xff);
if (in.remaining() > len) {
ByteBuffer buffer = ByteBuffer.allocate(len + 25);
byte[] bytes2 = new byte[len + 1];
in.get(bytes2);
buffer.put(start1).put(start2).put(bytes1).put(bytes2);
try {
Message msg = new Message();
msg.read(buffer.array());
out.write(msg);
} catch (Exception e) {
StringBuilder sb = new StringBuilder();
sb.append(" 协议解析异常:").append(buffer.array());
log.error(sb.toString(), e);
} finally {
if (AppProperties.isUprecord()) {
UpProtocolDataService.getInstance().write(buffer.array());
}
}
} else {
in.reset();
return false;
}
} else {
in.reset();
return false;
}
} else {
in.reset();
in.get();
}
} else {
if (AppProperties.isUprecord()) {
UpProtocolDataService.getInstance().write(new byte[]{ start1 });
}
}
}
return false;
}
}