使用mina2通信的完整代码朋友们可以去http://download.csdn.net/detail/u013378306/8756861下载
下面只对编解码协议进行解释
package lhy.charest;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import lhy.client_domain.MsgPack;
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;
/**
* @see 协议解码
* @author lhy
* @date
*/
public class MsgProtocolDecoder extends CumulativeProtocolDecoder {
private Charset charset=null;
public MsgProtocolDecoder() {
this(Charset.defaultCharset());
}
public MsgProtocolDecoder(Charset charset) {
this.charset = charset;
}
public void dispose(IoSession arg0) throws Exception {
}
protected boolean doDecode(IoSession session, IoBuffer ioBuffer, ProtocolDecoderOutput out) throws Exception {
ioBuffer.order(ByteOrder.LITTLE_ENDIAN);
MsgPack mp = (MsgPack) session.getAttribute("nac-msg-pack"); // 从session对象中获取“xhs-upload”属性值
if(null==mp){
if (ioBuffer.remaining() >= 8) {
//取消息体长度
int msgLength = ioBuffer.getInt();
int msgMethod = ioBuffer.getInt();
mp=new MsgPack();
mp.setMsgLength(msgLength);
mp.setMsgCode(msgMethod);
session.setAttribute("nac-msg-pack",mp);
return true;
}
return false;
}
//如果tcp缓冲区数据大于上次保存的的,解析消息体
if(ioBuffer.remaining()>=mp.getMsgLength()){
byte [] msgPack=new byte[mp.getMsgLength()];
ioBuffer.get(msgPack);
mp.setMsgPack(new String(msgPack,charset));
session.removeAttribute("nac-msg-pack");
out.write(mp);
return true;
}
return false;
}
}
package lhy.charest;
import java.io.NotSerializableException;
import java.io.Serializable;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import lhy.client_domain.MsgPack;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
/**
* 自定义编码
* @author Administrator
*
*/
public class MsgProtocolEncoder extends ProtocolEncoderAdapter{
private Charset charset=null;
public MsgProtocolEncoder(Charset charset) {
this.charset = charset;
}
//在此处实现对MsgProtocolEncoder包的编码工作,并把它写入输出流中
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
if(message instanceof MsgPack){
MsgPack mp = (MsgPack) message;
//第一个参数指定初始化容量,第
//二个参数指定使用直接缓冲区还是JAVA 内存堆的缓存区,默认为false。
IoBuffer buf = IoBuffer.allocate(mp.getMsgLength());
buf.order(ByteOrder.LITTLE_ENDIAN);
//这个方法设置IoBuffer 为自动扩展容量,也就是前面所说的长度可变,
buf.setAutoExpand(true);
//设置消息内容的长度
buf.putInt(mp.getMsgLength());
//设置消息的功能函数
buf.putInt(mp.getMsgCode());
if (null != mp.getMsgPack()) {
buf.put(mp.getMsgPack().getBytes(charset));
}
buf.flip();
out.write(buf);
out.flush();
buf.free();
}
}
public void dispose() throws Exception {
}
}