博客
关于我
随笔 @mina通讯框架
阅读量:275 次
发布时间:2019-03-01

本文共 5576 字,大约阅读时间需要 18 分钟。

夜光序言:

知道吗,世界上有一种东西叫做“执著”,

它会使你的生命散发光彩。

有了执著才有了说“不悔”的机会。

 

 

正文:

MINA框架的特点有:

基于java NIO类库开发;

采用非阻塞方式的异步传输;

事件驱动;支

持批量数据传输;

支持TCP、UDP协议;

控制反转的设计模式(支持Spring);

采用优雅的松耦合架构;

可灵活的加载过滤器机制;

单元测试更容易实现;

可自定义线程的数量,以提高运行于多处理器上的性能;

采用回调的方式完成调用,线程的使用更容易。

 

客户端:一个main,一个处理器

package mina;import java.net.InetSocketAddress;import java.nio.charset.Charset;import org.apache.mina.core.future.ConnectFuture;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.NioSocketConnector;public class MinaTimeClient {    public static void main(String[] args) {        // 创建客户端连接器.        NioSocketConnector connector = new NioSocketConnector();        connector.getFilterChain().addLast("logger", new LoggingFilter());        connector.getFilterChain().addLast(                "codec",                new ProtocolCodecFilter(new TextLineCodecFactory(Charset                        .forName("UTF-8")))); // 设置编码过滤器        connector.setConnectTimeout(30);        connector.setHandler(new TimeClientHandler());// 设置事件处理器        ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",                9123));// 建立连接        cf.awaitUninterruptibly();// 等待连接创建完成        cf.getSession().write("hello");// 发送消息        cf.getSession().write("quit");// 发送消息        cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开        connector.dispose();    }}
package mina;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;// 这个是用于客户端处理器/*author:Genius Team* *  */public class TimeClientHandler extends IoHandlerAdapter {    public TimeClientHandler() {    }    @Override    public void messageReceived(IoSession session, Object message)            throws Exception {        System.out.println("messageReceived method was called!");        System.out.println(message);// 显示接收到的消息    }    @Override    public void exceptionCaught(IoSession session, Throwable cause)            throws Exception {        // TODO Auto-generated method stub        super.exceptionCaught(session, cause);    }    @Override    public void messageSent(IoSession session, Object message) throws Exception {        // TODO Auto-generated method stub        super.messageSent(session, message);        System.out.println("messageSent method was called!");        System.out.println(message);    }    @Override    public void sessionClosed(IoSession session) throws Exception {        // TODO Auto-generated method stub        super.sessionClosed(session);        System.out.println("sessionClosed method was called!");    }    @Override    public void sessionCreated(IoSession session) throws Exception {        // TODO Auto-generated method stub        super.sessionCreated(session);        System.out.println("sessionCreated method was called!");    }    @Override    public void sessionIdle(IoSession session, IdleStatus status)            throws Exception {        // TODO Auto-generated method stub        super.sessionIdle(session, status);    }    @Override    public void sessionOpened(IoSession session) throws Exception {        // TODO Auto-generated method stub        super.sessionOpened(session);        System.out.println("sessionOpened method was called!");    }}

服务端:一个main,一个处理器

package test;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.charset.Charset;import org.apache.mina.core.service.IoAcceptor;import org.apache.mina.core.session.IdleStatus;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;// author:夜光public class MinaTimeServer {    private static final int PORT = 9123;    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 TimeServerHandler() );// 设置buffer的长度        acceptor.getSessionConfig().setReadBufferSize( 2048 );//设置连接超时时间        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );// 绑定端口        acceptor.bind( new InetSocketAddress(PORT) );    }}

 

package test;import java.util.Date;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;// 这个很关键,涉及到业务逻辑处理器代码public class TimeServerHandler extends IoHandlerAdapter{    //连接异常时处理方法    @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();        session.write( date.toString() );        System.out.println("Message written...");    }    @Override    public void sessionIdle( IoSession session, IdleStatus status ) throws Exception    {        System.out.println( "IDLE " + session.getIdleCount( status ));    }}

和我之前学的Netty异曲同工之妙~~

运行result:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载地址:http://lnbo.baihongyu.com/

你可能感兴趣的文章
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>