日期:2014-05-16  浏览次数:21072 次

Apache Mina的最简单例子
apache mina的下载地址:http://mina.apache.org/mina-project/downloads.html

1. 首先,要在classpath中配置以下的jar文件:
mina-core-2.0.7.jar
mina-example-2.0.7.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar
log4j-1.2.17.jar

2. 基本要素:
1) IoFilters
2) codec: ProtocolCodecFactory
3) business logic: IoHandler

2. 基于TCP的服务例子:
1) 服务Server端
定义Server服务的代码
public class DemoTimeServer {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		final int PORT = 9123;
		
		// 定义一个接收客户端请求的Acceptor
		IoAcceptor acceptor = new NioSocketAcceptor();
		
		// 1. 定义Logging的IoFilters
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		// 2. 定义解析器的IoFilters,将客户端传入的流或协议数据按照定义的解析器进行解析
		acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));
		
		// 3. 设置业务处理机制,定义接收连接后的信息接收,信息回复的处理方法
		acceptor.setHandler(new DemoTimeServerHandler());
		//NioSocketAcceptor配置		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		
		//定义完成,绑定端口
		acceptor.bind(new InetSocketAddress(PORT));
	}

}


定义处理Server端业务逻辑的代码
public class DemoTimeServerHandler implements IoHandler {

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();

	}

        // 接收到来自客户端的消息后,对消息进行处理,并将处理后的消息回复客户端
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String str = message.toString();
		if(str.trim().equalsIgnoreCase("quit")){
			session.close(true);
			return;
		}
		Date date = new Date();
		str = str + ", receiving date(" + date.toString() + ")";
		session.write(str);
		System.out.println("message write..." + str + ", writing date(" + date.toString());

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		String str = message.toString();
		System.out.println("message sent..." + str);

	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("CLOSED " + session.getReadMessages());

	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("CREATED " + session.getCreationTime());

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		System.out.println("IDEL " + session.getIdleCount(status));

	}

	@Override
	public void sessionOpened(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub

	}

}


2) 客户Client端
定义客户端链接服务端的代码
public class DemoTimeClient {

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {

	 // 创建一个客户端连接
     NioSocketConnector connector = new NioSocketConnector();
        
         //1. 定义Logging的 IoFilters
         connector.getFilterChain().addLast("logger", new LoggingFilter());
   	 // 2.定义解析器的IoFilters,将发出的信息按照定义的解析器进行解析
         connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));

   	 // 3.设置业务处理机制,定义链接后的信息发送,接收回复信息的处理方法
     DemoTimeClientHandler handler = new DemoTimeClientHandler("i am jeanjeanfang, hello dear!");
     connector.setHandler(handler);
       
     // 4. 链接服务端
	 IoSession session;
	 for (;;) {
	    
	    	try {
	        
	    		ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9123));
	            future.awaitUninterruptibly();
	            session = future.getSession();
	            break;
	        } catch (RuntimeIoException e) {
	            System.err.println("Failed to connect.");
	            e.printStackTrace();
	            Thread.sleep(500