1. 程式人生 > >mina 自定義包的解析

mina 自定義包的解析

首先定義自動定義的包類

package com.lianshang.findme.common.message;


import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;


import org.apache.mina.core.buffer.IoBuffer;


import com.lianshang.findme.common.opcode.MsgCode;


public class MessagePackage
{
private int opcode;
private int length;
private IoBufferstream;
private Charset charset;


public MessagePackage()
{
charset = Charset.forName("utf-8");
clear();
}

public MessagePackage(Charset _charset)
{
charset = _charset;
clear();
}

public void clear()
{
opcode = MsgCode.CODE_BEGIN;
length = 0;
stream = IoBuffer.allocate(100).setAutoExpand(true);
}
public void readBuffer(IoBuffer in)
{
opcode = in.getInt();
length = in.getInt(); 
byte[] data = new byte[length];
in.get(data);

stream.put(data);
stream.flip();
}

public void writeBuffer(IoBuffer out)
{
out.putInt(opcode);
out.putInt(length);
byte[] data = new byte[length];
stream.get(data);
out.put(data);
}

public void flip()
{
stream.flip();
length = stream.remaining(); 
}

public void putString (String _String)
{
CharsetEncoder encoder = charset.newEncoder();
try
{
int length =_String.getBytes().length;
stream.putInt(length);
stream.putString(_String,encoder);
} catch (CharacterCodingException e)
{
e.printStackTrace();
}
}

public String getString()
{
CharsetDecoder decoder = charset.newDecoder();
int length = stream.getInt();

String _str = null;
try
{
_str = stream.getString(length,decoder);
} catch (CharacterCodingException e)
{
e.printStackTrace();
}
return _str;
}

public void putBoolean(boolean val)
{
byte a = (byte) (val ? 1 : 0);
stream.put(a);
}
public boolean getBoolean()
{
return stream.get() == ((byte)1);
}

public void putInt(int val)
{
stream.putInt(val);
}
public int getInt()
{
return stream.getInt();
}

public void putDouble(double val)
{
stream.putDouble(val);
}
public double getDouble()
{
return stream.getDouble();
}

public int getOpcode()
{
return opcode;
}


public void setOpcode(int opcode)
{
this.opcode = opcode;
}


public int getLength()
{
return length;
}

public String toString()
{
return "\n"+"opcode:"+opcode+"DataLength:"+length;
}


}

再定義Decode 和Encode

package com.lianshang.findme.common.message;


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.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.lianshang.findme.common.opcode.MsgCode;


public class MyMessageDecoder implements MessageDecoder
{
private Logger logger = LoggerFactory.getLogger(MyMessageDecoder.class);


public MyMessageDecoder()
{
}


// 檢查給定的IoBuffer是否適合解碼
public MessageDecoderResult decodable(IoSession session, IoBuffer in)
{
// 報頭長度==8
if (in.remaining() < 8)
{
return MessageDecoderResult.NEED_DATA;
}


int opcode = in.getInt();
if (opcode > MsgCode.CODE_BEGIN && opcode < MsgCode.CODE_COUNT)
{
//logger.info("請求識別符號:" + opcode);
} else
{
logger.error("未知的解碼型別....");
return MessageDecoderResult.NOT_OK;


// 真實資料長度
int len = in.getInt();
if (in.remaining() < len)
{
return MessageDecoderResult.NEED_DATA;
}
return MessageDecoderResult.OK;
}


public MessageDecoderResult decode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception
{
MessagePackage message = new MessagePackage();
message.readBuffer(in);
out.write(message);
return MessageDecoderResult.OK;
}


public void finishDecode(IoSession session, ProtocolDecoderOutput out)
throws Exception
{


}
}

package com.lianshang.findme.common.message;




import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MyMessageEncoder implements MessageEncoder<MessagePackage>
{
private Logger logger = LoggerFactory.getLogger(MyMessageEncoder.class);


public MyMessageEncoder()
{


}


public void encode(IoSession session, MessagePackage message,
ProtocolEncoderOutput out) throws Exception
{
IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
message.writeBuffer(buf);
buf.flip();
out.write(buf);
}
}

--------------------

coderfactory

package com.lianshang.findme.common.message;




import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageEncoder;


public class MyMessageCodecFactory extends DemuxingProtocolCodecFactory
{
private MessageDecoder decoder;
private MessageEncoder<MessagePackage> encoder;


// 註冊編解碼器
public MyMessageCodecFactory(MessageDecoder decoder,
MessageEncoder<MessagePackage> encoder)
{
this.decoder = decoder;
this.encoder = encoder;
addMessageDecoder(this.decoder);
addMessageEncoder(MessagePackage.class, this.encoder);
}
}

新增自定義的過濾器

final IoConnector connector = new NioSocketConnector();
// 建立連線
// 設定連結超時時間
connector.setConnectTimeoutMillis(10000);
// 新增過濾器
connector.getFilterChain().addLast(
// 新增訊息過濾器
"codec",
new ProtocolCodecFilter(new MyMessageCodecFactory(
new MyMessageDecoder(), new MyMessageEncoder())));

大功告成,自定義的訊息過濾器搞定,有不明白的同學可以留言交流