mina的简单例子

这个例子是提供的示例,简单的加下注释。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

public class MinaTimeServer {

private static final int PORT = 9123;

public static void main(String[] args) throws IOException {
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
//IoAcceptor负责配置服务器端的IO事件处理线程池、消息发送和FilterChain等等
IoAcceptor acceptor = new SocketAcceptor();
//用于对AoAccepter进行配置,这里配置了一个日志,另一个过滤器功能是This filter will translate binary or //protocol specific data into message object and vice versa(待议)
SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getFilterChain().addLast( "logger", new LoggingFilter() );
cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
//绑定端口、处理器以及配置
acceptor.bind( new InetSocketAddress(PORT), new TimeServerHandler(), cfg);
System.out.println("MINA Time server started.");
}
}
处理器要实现IoHandlerAdapter 接口,这里的实现如下:
public class TimeServerHandler extends IoHandlerAdapter {
public void exceptionCaught(IoSession session, Throwable t) throws Exception {
t.printStackTrace();
session.close();
}

public void messageReceived(IoSession session, Object msg) throws Exception {
String str = msg.toString();
if( str.trim().equalsIgnoreCase("quit") ) {
session.close();
return;
}

Date date = new Date();
session.write( date.toString() );
System.out.println("Message written...");
}

public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");

if( session.getTransportType() == TransportType.SOCKET )
((SocketSessionConfig) session.getConfig() ).setReceiveBufferSize( 2048 );

session.setIdleTime( IdleStatus.BOTH_IDLE, 10 );
}
}
启动服务器后就可以在客户端访问服务了。
Client Output Server Output 
user@myhost:~> telnet 127.0.0.1 9123 
Trying 127.0.0.1... 
Connected to 127.0.0.1. 
Escape character is '^]'. 
hello 
Mon Apr 09 23:42:55 EDT 2007 
quit 
Connection closed by foreign host. 
user@myhost:~>
MINA Time server started. 
Session created... 
Message written...
另外一个问题就是将SocketAcceptor配置成多线程的,如下:
SocketAcceptor acceptor = new SocketAcceptor(Runtime.getRuntime().availableProcessors() + 1, Executors.newCachedThreadPool());
其中
Runtime.getRuntime().availableProcessors()是处理器的个数,后边
Executors.newCachedThreadPool()是线程池功能。
关于待议的那部分,需要参考http://mina.apache.org/tutorial-on-protocolcodecfilter.html

明天继续吧~
另外session.write并不能保证成功写入发送缓冲区,为了确定是否成功,可以采用如下办法:
WriteFuture writeResult=session.write(data);
writeResult.addListener(new IOFutureListener){
public void operationCompleted(IOFuture future)
{ WriteFuture wfuture=(WriteFuture)future;
if(wfuture.isWritten())
return;
else{
//处理
}
}
}
原文地址:https://www.cnblogs.com/macula7/p/1960397.html