67,512
社区成员
发帖
与我相关
我的任务
分享
public class ServerMessageDecoder extends CumulativeProtocolDecoder {
private final Charset charset = Charset.forName("UTF-8");
private IoBuffer buff = IoBuffer.allocate(320).setAutoExpand(true);
//private static int count = 0;
@Override
public boolean doDecode(IoSession iosession, IoBuffer iobuffer, ProtocolDecoderOutput out) throws Exception {
...;
}
private final Charset charset = Charset.forName("UTF-8");
//private IoBuffer buff = IoBuffer.allocate(320).setAutoExpand(true);
private final AttributeKey CONTEXT = new AttributeKey(getClass(), "context");
private Context getContext(IoSession session) {
Context context = (Context) session.getAttribute(CONTEXT);
if (null == context) {
context = new Context();
session.setAttribute(CONTEXT, context);
}
return context;
}
@Override
public boolean doDecode(IoSession iosession, IoBuffer iobuffer, ProtocolDecoderOutput out) throws Exception {
boolean complete = false;
Context ctx = this.getContext(iosession);
ctx.append(iobuffer);
IoBuffer buf = ctx.getBuffer();
buf.flip();
while (buf.hasRemaining()) {
byte b = buf.get();
/**
* CIMConstant.MESSAGE_SEPARATE 为消息界限
* 当一次收到多个消息时,以此分隔解析多个消息
*/
if (b == CIMConstant.MESSAGE_SEPARATE ) {
complete = true;
break;
} /*else {
buff.put(b);
}*/
}
if (complete) {
buf.flip();
byte[] bytes = new byte[buf.limit()-1];
buf.get(bytes);
String message = new String(bytes, charset);
buf.clear();
ctx.reset();
System.out.println("iosessionid = " + iosession.getId() +" &&&&&&&&&&&&& = " +message);
SentBody body = new SentBody();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(message.getBytes(charset)));
body.setKey(doc.getElementsByTagName("key").item(0).getTextContent());
NodeList items = doc.getElementsByTagName("data").item(0).getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node node = items.item(i);
body.getData().put(node.getNodeName(), node.getTextContent());
}
out.write(body);
}
return complete;
}
private class Context {
private final IoBuffer innerBuffer;
public Context() {
innerBuffer = IoBuffer.allocate(320).setAutoExpand(true);
}
public void reset() {
this.innerBuffer.clear();
}
public void append(IoBuffer in) {
innerBuffer.put(in);
}
public IoBuffer getBuffer() {
return this.innerBuffer;
}
}