MINA对接某道闸例子

公司需要和道闸对接,道闸有个模拟客户端端定时发送数据,服务端将道闸产生的socket报文进行解析,报文里面有文案中规定好的数据含义。某种意义上讲,socket报文也是处理异构跨平台数据交换的利器。基于TCP/UDP协议,数据格式为字符串,这也跨语言平台无差别交换的原因。

扩展一下,有类似的框架Netty,可以参考MINA与Netty的对比文章:

http://ifeve.com/netty-mina-in-depth-1/

packagecom.jq.test;

importjava.io.IOException;

importjava.net.InetSocketAddress;

importorg.apache.mina.filter.executor.ExecutorFilter;

importorg.apache.mina.filter.executor.UnorderedThreadPoolExecutor;

importorg.apache.mina.filter.logging.LoggingFilter;

importorg.apache.mina.transport.socket.DatagramSessionConfig;

importorg.apache.mina.transport.socket.nio.NioDatagramAcceptor;

publicclassMinaUdpServer{

//服务器监听端口

privatestaticfinalintPORT=1002;

/**

*

*/

publicMinaUdpServer(){

//TODOAuto-generatedconstructorstub

}

/**

*@paramargs

*@throwsIOException

*/

publicstaticvoidmain(String[]args)throwsIOException{

NioDatagramAcceptoracceptor=newNioDatagramAcceptor();//创建一个UDP的接收器

acceptor.setHandler(newUdpServerHandler());//设置接收器的处理程序

//ExecutorthreadPool=Executors.newCachedThreadPool();//建立线程池

UnorderedThreadPoolExecutorpool=newUnorderedThreadPoolExecutor(10);

acceptor.getFilterChain().addLast("exector",newExecutorFilter(pool));

acceptor.getFilterChain().addLast("logger",newLoggingFilter());

DatagramSessionConfigdcfg=acceptor.getSessionConfig();//建立连接的配置文件

dcfg.setReadBufferSize(4096);//设置接收最大字节默认2048

dcfg.setReceiveBufferSize(1024);//设置输入缓冲区的大小

dcfg.setSendBufferSize(1024);//设置输出缓冲区的大小

dcfg.setReuseAddress(true);//设置每一个非主监听连接的端口可以重用

acceptor.bind(newInetSocketAddress(PORT));//绑定端口}

}

}

packagecom.jq.test;

importjava.util.Date;

importorg.apache.mina.core.buffer.IoBuffer;

importorg.apache.mina.core.service.IoHandlerAdapter;

importorg.apache.mina.core.session.IoSession;

/**

*继承自IoHandlerAdapter,IoHandlerAdapter继承接口IoHandler

类IoHandlerAdapter实现了IoHandler的所有方法,只要重载关心的几个方法就可以了

*/

publicclassUdpServerHandlerextendsIoHandlerAdapter{

@Override

publicvoidexceptionCaught(IoSessionsession,Throwablecause)

throwsException{

cause.printStackTrace();

}

/*

*这个方法是目前这个类里最主要的,

*当接收到消息,只要不是quit,就把服务器当前的时间返回给客户端

*如果是quit,则关闭客户端连接*/

@Override

publicvoidmessageReceived(IoSessionsession,Objectmessage)

throwsException{

System.out.println("messageReceived");

if(messageinstanceofIoBuffer){

IoBufferioBuffer=(IoBuffer)message;

byte[]getInfo=newbyte[ioBuffer.limit()];

ioBuffer.get(getInfo);

StringgetInfoStr=printHexString(getInfo);

System.out.println(Thread.currentThread().getName()+"["+newDate()+"]receive:"+getInfoStr);

IoBufferbuffer1=IoBuffer.wrap("0".getBytes());//返回信息给Clinet端

session.write(buffer1);

Thread.sleep(10000);

}

}

@Override

publicvoidsessionClosed(IoSessionsession)throwsException{

//TODOAuto-generatedmethodstub

super.sessionClosed(session);

System.out.println("客户端与服务端断开连接.....");

}

publicstaticStringprintHexString(byte[]b){

Stringresult="";

for(inti=0;i<b.length;i++){

Stringhex=Integer.toHexString(b[i]&0XFF);

if(hex.length()==1){

hex='0'+hex;

}

result=result+hex.toUpperCase();

}

returnresult.trim();

}

}

packagecom.jq.test;

importjava.io.IOException;

importjava.net.InetSocketAddress;

importorg.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;

importorg.apache.mina.filter.codec.ProtocolCodecFilter;

importorg.apache.mina.filter.codec.textline.TextLineCodecFactory;

importorg.apache.mina.transport.socket.SocketAcceptor;

importorg.apache.mina.transport.socket.nio.NioSocketAcceptor;

publicclassMinaTcpServer{

privatestaticMinaTcpServerminaServer=null;

//创建一个非阻塞的Server端Socket

privateSocketAcceptoracceptor=newNioSocketAcceptor();

//创建接收数据的过滤器

privateDefaultIoFilterChainBuilderchain=acceptor.getFilterChain();

privateintbindPort=1002;

//单例

publicstaticMinaTcpServergetInstances(){

if(null==minaServer){

minaServer=newMinaTcpServer();

}

returnminaServer;

}

privateMinaTcpServer(){

//设定这个过滤器将按对象读取数据

//单例模式----------------------------------------

//chain.addLast("myChin",newProtocolCodecFilter(

//newObjectSerializationCodecFactory()));

//设定服务器端的消息处理器:一个MinaServerHandler对象,

//acceptor.setHandler(ServerHandler.getInstances());

//非单例模式---------------------------------------

//接收文字

chain.addLast("myChin",newProtocolCodecFilter(

newTextLineCodecFactory()));

//接收对象

//chain.addLast("myChin",newProtocolCodecFilter(

//newObjectSerializationCodecFactory()));

acceptor.setHandler(newTcpServerHandler());

try{

//绑定端口,启动服务器

acceptor.bind(newInetSocketAddress(bindPort));

}catch(IOExceptione){

e.printStackTrace();

}

System.out.println("服务端:监听端口--->"+bindPort);

}

publicstaticvoidmain(String[]args)throwsException{

MinaTcpServer.getInstances();

//newMinaServer();

}

}

packagecom.jq.test;

importjava.net.InetSocketAddress;

importorg.apache.mina.core.filterchain.IoFilterAdapter;

importorg.apache.mina.core.service.IoHandler;

importorg.apache.mina.core.session.IdleStatus;

importorg.apache.mina.core.session.IoSession;

publicclassTcpServerHandlerextendsIoFilterAdapterimplementsIoHandler{

privatestaticTcpServerHandlersamplMinaServerHandler=null;

publicstaticTcpServerHandlergetInstances(){

if(null==samplMinaServerHandler){

samplMinaServerHandler=newTcpServerHandler();

}

returnsamplMinaServerHandler;

}

publicTcpServerHandler(){

}

publicvoidsessionOpened(IoSessionsession)throwsException{

System.out.println("服务端:会话打开");

}

publicvoidsessionClosed(IoSessionsession){

}

publicvoidmessageReceived(IoSessionsession,Objectmessage)throwsException{

//接收字符串

Stringstr=(String)message;

System.out.println("服务端:收到客户端发来的信息--->"+str);

System.out.println("客户端"+((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress()+"连接成功!");

}

publicvoidexceptionCaught(IoSessionarg0,Throwablearg1)throwsException{

}

publicvoidmessageSent(IoSessionarg0,Objectarg1)throwsException{

}

publicvoidsessionCreated(IoSessionarg0)throwsException{

System.out.println("服务端:会话创建");

}

publicvoidsessionIdle(IoSessionarg0,IdleStatusarg1)throwsException{

}

@Override

publicvoidinputClosed(IoSessionarg0)throwsException{

//TODOAuto-generatedmethodstub

}

}