初识mina框架

step1:创建java工程,导入jar包

  

step2:在src下配置log4j.properties文件

 1 log4j.rootLogger=DEBUG,MINA,file
 2 log4j.appender.MINA=org.apache.log4j.ConsoleAppender
 3 log4j.appender.MINA.layout=org.apache.log4j.PatternLayout
 4 log4j.appender.MINA.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS}%-5p%c{1}%x-%m%n
 5 log4j.appender.file=org.apache.log4j.RollingFileAppender
 6 log4j.appender.file.File=./log/minademos.log
 7 log4j.appender.file.MaxFileSize=5120KB
 8 log4j.appender.file.MaxBackupIndex=10
 9 log4j.appender.file.layout=org.apache.log4j.PatternLayout
10 log4j.appender.file.layout.ConversionPattern=[VAMS][%d]%p|%m|[%t]%C.%M(%L)%n

step3:服务器端代码

 1 package com.per.mina.server;
 2 
 3 import java.net.InetSocketAddress;
 4 import java.nio.charset.Charset;
 5 
 6 import org.apache.log4j.Logger;
 7 import org.apache.mina.core.service.IoAcceptor;
 8 import org.apache.mina.core.session.IdleStatus;
 9 import org.apache.mina.filter.codec.ProtocolCodecFilter;
10 import org.apache.mina.filter.codec.textline.LineDelimiter;
11 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
12 import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
13 
14 import com.per.mina.server.handler.Demo1ServerHandler;
15 
16 public class Demo1Server {
17     private static Logger logger=Logger.getLogger(Demo1Server.class);
18     private static int port=3005;
19     public static void main(String[] args) {
20         IoAcceptor acceptor=null;//创建连接
21         try {
22             acceptor=new NioSocketAcceptor();//创建一个非阻塞的serverdaunt的Socket
23             //添加消息过滤器
24             acceptor.getFilterChain().addLast("codec", 
25                     new ProtocolCodecFilter(
26                             new TextLineCodecFactory(Charset.forName("utf-8"),
27                                         LineDelimiter.WINDOWS.getValue(), 
28                                         LineDelimiter.WINDOWS.getValue())));
29             //设置读取数据的缓冲区大小
30             acceptor.getSessionConfig().setReadBufferSize(2048);
31             //读写通道10 秒内无操作进入空闲状态
32             acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
33             //绑定逻辑处理器
34             acceptor.setHandler(new Demo1ServerHandler());//添加业务处理
35             
36             //绑定端口
37             acceptor.bind(new InetSocketAddress(port));
38             logger.info("服务器端启动成功...  端口号为:"+port);
39         } catch (Exception e) {
40             logger.error("服务器端启动异常...", e);
41             e.printStackTrace();
42         }
43         
44     }
45 }
 1 package com.per.mina.server.handler;
 2 
 3 import java.util.Date;
 4 
 5 import org.apache.log4j.Logger;
 6 import org.apache.mina.core.service.IoHandlerAdapter;
 7 import org.apache.mina.core.session.IdleStatus;
 8 import org.apache.mina.core.session.IoSession;
 9 
10 public class Demo1ServerHandler extends IoHandlerAdapter {
11     private static Logger logger=Logger.getLogger(Demo1ServerHandler.class);
12     
13     @Override
14     public void sessionCreated(IoSession session) throws Exception {
15         logger.info("服务器端与客户端创建连接");
16     }
17     @Override
18     public void sessionOpened(IoSession session) throws Exception {
19         logger.info("服务端与客户端连接打开");
20     }
21     @Override
22     public void messageReceived(IoSession session, Object message)
23             throws Exception {
24         String msg=message.toString();
25         logger.info("服务端接收到的数据为:"+msg);
26         if("bye".equals(msg)){
27             session.close();
28         }
29         Date date=new Date();
30         session.write(date);
31     }
32     @Override
33     public void messageSent(IoSession session, Object message) throws Exception {
34         //session.closeNow();//控制长连接与短连接
35         logger.info("服务端发送信息成功...");
36     }
37     @Override
38     public void sessionClosed(IoSession session) throws Exception {
39         super.sessionClosed(session);
40     }
41     @Override
42     public void sessionIdle(IoSession session, IdleStatus status)
43             throws Exception {
44         logger.info("服务端进入空闲状态...");
45     }
46     @Override
47     public void exceptionCaught(IoSession session, Throwable cause)
48             throws Exception {
49         logger.error("服务端发送异常", cause);
50     }
51     
52 }

step4:客户端代码

 1 package com.per.mina.client;
 2 
 3 import java.net.InetSocketAddress;
 4 import java.nio.charset.Charset;
 5 
 6 
 7 
 8 import org.apache.mina.core.future.ConnectFuture;
 9 import org.apache.mina.core.service.IoConnector;
10 import org.apache.mina.core.session.IoSession;
11 import org.apache.mina.filter.codec.ProtocolCodecFilter;
12 import org.apache.mina.filter.codec.textline.LineDelimiter;
13 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
14 import org.apache.mina.transport.socket.nio.NioSocketConnector;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17 
18 import com.per.mina.client.handler.MinaClientDemo1Handler;
19 
20 public class MinaClientDemo1 {
21     //private static Logger logger=Logger.getLogger(MinaClientDemo1.class);
22     private static Logger logger=LoggerFactory.getLogger(MinaClientDemo1.class);
23     private static String HOST="127.0.0.1";
24     private static int PORT=3005;
25     public static void main(String[] args) {
26         //创建一个非阻塞的客户端程序
27         IoConnector connector=new NioSocketConnector();//创建连接
28         
29         //设置连接超时时间
30         connector.setConnectTimeoutMillis(30000);
31         //添加过滤器
32         connector.getFilterChain().addLast("codec", 
33                 new ProtocolCodecFilter(new TextLineCodecFactory(
34                         Charset.forName("utf-8"), 
35                         LineDelimiter.WINDOWS.getValue(),
36                         LineDelimiter.WINDOWS.getValue())));
37         //添加业务逻辑处理器类
38         connector.setHandler(new MinaClientDemo1Handler());//添加业务处理
39         IoSession session=null;
40         try {
41             ConnectFuture future=connector.connect(new InetSocketAddress(HOST, PORT));//创建连接
42             future.awaitUninterruptibly();//等待连接完成
43             session=future.getSession();//获得session
44             session.write("test mina");//发送消息
45             
46             
47         } catch (Exception e) {
48             logger.error("客户端连接异常...", e);
49         }
50         session.getCloseFuture().awaitUninterruptibly();//等待连接断开
51         connector.dispose();
52     }
53 }
package com.per.mina.client.handler;

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

public class MinaClientDemo1Handler extends IoHandlerAdapter{
    private static Logger logger=Logger.getLogger(MinaClientDemo1Handler.class);
    @Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        String msg=message.toString();
        logger.info("客户端接收到的信息为:"+msg);
    }
    
    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        logger.error("客户端发生异常",cause);
    }
}

 step5:进行测试,先运行服务端,再运行客户端

转载于:https://www.cnblogs.com/s-d-g/p/8569049.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值