使用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);
}
import java.io.notserializableexception;
import java.io.serializable;
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 {