Mina框架实例

来源:互联网 发布:软件测试就业培训 编辑:程序博客网 时间:2024/05/22 13:14

简介

Apache MINA 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP 协议栈的通信框架。
这里写图片描述
从MINA 的框架图可以看出,Mina 位于用户应用程序和底层java 网络API之间。我们开发基于mina的网络应用程序,就无需关心复杂的通信细节。

框架流程图

这里写图片描述
服务器端(右图)监听指定端口上到来的请求,对请求进行处理后,回复响应。它也会创建并处理一个连接过来的客户会话对象(session)
客户端(左) :连接到服务器端、 向服务器发送消息、 等待服务器端响应,并处理响应

接口说明

IoService
IoService实现了对网络通信的客户端和服务端之间的抽象,用于描述客户端的子接口IoConnector。并且可以管理连接双方的会话session,同样可以添加过滤器。

IoServiceListener
IoServiceListener是IoService的监听器,监听与该IoService相关的所有事件。

IoSession
IoSession表示一个活动的网络连接,与所使用的传输方式无关。IoSession可以用来存储用户自定义的与应用相关的属性。这些属性通常用来保存应用的状态信息,还可以用来在IoFilter器和IoHandler之间交换数据。
IoProcessor
IoProcessor,负责IoFilter和IoHandler进行具体处理,用于为IoSession执行具体的I/O操作。IoProcessor 负责调用注册在IoService上的过滤器,并在过滤器链之后调用IoHandler。一个Processor可以对应N个IoSessions,一个IoSession总是对应一个IoProcessor。
IoFilter
IoFilter是IoServer和IoHander之间的桥梁,从 I/O 服务发送过来的所有 I/O 事件和请求,在到达 I/O 处理器之前,会先由 I/O 过滤器链中的 I/O 过滤器进行处理,比如记录日志、性能分析、访问控制、负载均衡和消息转换等。
IoHandler
IoHandler负责业务处理的,是I/O事件真正得到处理的地方,包含以下一些方法作为业务处理的扩展点

实例

  1. Server 端
public class MinaServer {    static int PORT = 7080;    static IoAcceptor acceptor = null;    public static void main(String[] args) {        try {            acceptor = new NioSocketAcceptor();            // 设置编码过滤器            acceptor.getFilterChain().addLast(                    "codec",                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset                            .forName("UTF-8"),                            LineDelimiter.WINDOWS.getValue(),                            LineDelimiter.WINDOWS.getValue())));            acceptor.getSessionConfig().setReadBufferSize(1024);            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);            acceptor.setHandler(new MyHandler());            acceptor.bind(new InetSocketAddress(PORT));            System.out.println("Server->" + PORT);        } catch (IOException e) {            e.printStackTrace();        }    }}
  1. Server 端的Handler 处理
public class MyHandler extends IoHandlerAdapter {    @Override    public void exceptionCaught(IoSession session, Throwable cause)            throws Exception {        System.out.println("exceptionCaught");    }    @Override    public void messageReceived(IoSession session, Object message)            throws Exception {        String msg = (String) message;        System.out.println("服务器端接收数据:" +msg);        if(msg.equals("exit")){            session.close();        }        Date date = new Date();         session.write(date);    }    @Override    public void messageSent(IoSession session, Object message) throws Exception {        System.out.println("messageSent");    }    @Override    public void sessionClosed(IoSession session) throws Exception {        System.out.println("sessionClosed");    }    @Override    public void sessionCreated(IoSession session) throws Exception {        System.out.println("sessionCreated");    }    @Override    public void sessionIdle(IoSession session, IdleStatus status)            throws Exception {        System.out.println("sessionIdle");    }    @Override    public void sessionOpened(IoSession session) throws Exception {        System.out.println("sessionOpened");    }}
  1. Client端
public class MinaClient {    private static String host = "127.0.0.1";    private static int port =7080;    public static void main(String[] args) {        IoConnector connector = new NioSocketConnector();         IoSession session = null;        connector.setConnectTimeout(300);        //设置过滤器        connector.getFilterChain().addLast("coderc",                new ProtocolCodecFilter(                new TextLineCodecFactory(Charset.forName("UTF-8"),                        LineDelimiter.WINDOWS.getValue(),                        LineDelimiter.WINDOWS.getValue())));         connector.setHandler(new MyClientHandler());        ConnectFuture future =  connector.connect(new InetSocketAddress(host,port));        future.awaitUninterruptibly(); //等待我们的连接        session = future.getSession();  //获取会话        session.write("你好,Tonny!");        session.getCloseFuture().awaitUninterruptibly(); //等待关闭连接        connector.dispose();    }}
  1. client 端的业务处理
public class MyClientHandler extends IoHandlerAdapter{    @Override    public void exceptionCaught(IoSession session, Throwable cause)            throws Exception {        System.out.println("exceptionCaught");    }    @Override    public void messageReceived(IoSession session, Object message)            throws Exception {        String msg= (String) message;        System.out.println("客户端收到数据!");    }    @Override    public void messageSent(IoSession session, Object message) throws Exception {        System.out.println("messageSent");    }    @Override    public void sessionClosed(IoSession session) throws Exception {        System.out.println("sessionClosed");    }    @Override    public void sessionCreated(IoSession session) throws Exception {        System.out.println("sessionCreated");    }    @Override    public void sessionIdle(IoSession session, IdleStatus status)            throws Exception {        System.out.println("sessionIdle");    }    @Override    public void sessionOpened(IoSession session) throws Exception {        System.out.println("sessionOpened");    }}

测试上述服务器端与客户端交互,首先启动服务器端,监听7080端口。
接着启动客户端,连接到服务器端8080端口,然后发送消息,服务器端接收到消息后,直接将到客户端的连接关闭掉。
服务器端输出结果:
Server->7080
sessionCreated
sessionOpened
服务器端接收数据:你好,Tonny!
messageSent
客户端输出结果:
sessionCreated
sessionOpened
messageSent
客户端收到数据!

原创粉丝点击