MINA的第一个小小的例子

今天在别人的博客上看到过Apache的NIO框架MINA比较感兴趣,所以就参考别人的列子,自己动手配置运行了一下,感觉真是很爽。
1:首先下载MINA2的jar与其相关的jar包。
导入需要的jar包,如图。
MINA的第一个小小的例子
2:构建CalculatorHandler类

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;



 public class CalculatorHandler extends IoHandlerAdapter { 
    private static final Logger LOGGER = Logger.getLogger(CalculatorHandler.class); 

    private ScriptEngine jsEngine = null; 

    public CalculatorHandler() { 
        ScriptEngineManager sfm = new ScriptEngineManager(); 
        jsEngine = sfm.getEngineByName("JavaScript"); 
        if (jsEngine == null) { 
            throw new RuntimeException("找不到 JavaScript 引擎。"); 
        } 
    } 

    public void exceptionCaught(IoSession session, Throwable cause) 
        throws Exception { 
        LOGGER.warn(cause.getMessage(), cause); 
    } 

    public void messageReceived(IoSession session, Object message) 
        throws Exception { 
        String expression = message.toString(); 
        if ("quit".equalsIgnoreCase(expression.trim())) { 
            session.close(true); 
            return; 
        } 
        try { 
            Object result = jsEngine.eval(expression); 
            session.write(result.toString()); 
        } catch (ScriptException e) { 
            LOGGER.warn(e.getMessage(), e); 
            session.write("Wrong expression, try again."); 
        } 
    } 
}



3:构建CalculatorServer类
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;



public class CalculatorServer { 
    private static final int PORT = 10010; 

    private static final Logger LOGGER = Logger.getLogger(CalculatorServer.class); 

    public static void main(String[] args) throws IOException { 
        IoAcceptor acceptor = new NioSocketAcceptor(); 

        acceptor.getFilterChain().addLast("logger", new LoggingFilter()); 
        acceptor.getFilterChain().addLast( 
            "codec", 
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset 
                .forName("UTF-8")))); 

        acceptor.setHandler(new CalculatorHandler()); 
        acceptor.bind(new InetSocketAddress(PORT)); 

        LOGGER.info("计算器服务已启动,端口是" + PORT); 
    } 
}




4: 使用 Telnet 工具测试计算器服务


运行后的界面

MINA的第一个小小的例子

5:因为小弟刚学,这是第一个例子感觉比较新奇,希望大神们能够分享这方面的学习资料


你可能感兴趣的:(apache,Mina)