Apache MINA学习之路(1)


 1,Apache Mina 也称为:
     ●
NIO 框架

     ● 客户端/服务端框架(典型的 C/S 架构)
     ● 网络套接字(networking socket)类库

 

2,所要加载的包

     Apache MINA学习之路(1)_第1张图片
 

3,Mina 的执行流程
        Apache MINA学习之路(1)_第2张图片

 

4,服务端程序

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
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.transport.socket.nio.NioSocketAcceptor;

public class Demo1Server {
	private static Logger logger =Logger.getLogger(Demo1Server.class);
	private static int PORT = 8888;
	
	public static void main(String[] args) {
		IoAcceptor acceptor  = null;
		try {
		//创建一个非阻塞的server端的Socket
		acceptor = new NioSocketAcceptor();
		//创建接收数据的过滤器
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		//设置过滤器(使用Mina提供的文本换行符编解码器)
		chain.addLast("myChin", new ProtocolCodecFilter(new TextLineCodecFactory()));
		//new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue()));
		// 绑定逻辑处理器
		acceptor.setHandler(new Demo1ServerHandler());
		// 绑定端口
		acceptor.bind(new InetSocketAddress(PORT));
		logger.info("服务已启动... 端口号为:" + PORT);
		} catch (IOException e) {
			logger.error("服务端启动异常....", e);
			e.printStackTrace();
		}
		
	}
}

 

    逻辑处理器

import java.util.Date;

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

public class Demo1ServerHandler extends IoHandlerAdapter {
	public static Logger logger = Logger.getLogger(Demo1ServerHandler.class);

	public void sessionCreated(IoSession session) throws Exception {
		logger.info("服务端与客户端创建连接...");
	}

	public void sessionOpened(IoSession session) throws Exception {
		logger.info("服务端与"+session.getRemoteAddress()+"客户端连接打开...");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		String msg = message.toString();
		logger.info("服务端接收到的数据为:" + msg);
		if ("bye".equals(msg)) { // 服务端断开连接的条件
			session.close(true);
		}
		Date date = new Date();
		session.write(date);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
                //session.close(); //发送成功后主动断开与客户端的连接(短连接时使用)
		logger.info("服务端发送信息成功...");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
	}

	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		logger.info("服务端进入空闲状态...");
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.error("服务端发送异常...", cause);
	}
}

   测试:cmd -> telnet localhost 8888

 

 5,客户端程序

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient01 {
	private static Logger logger = Logger.getLogger(MinaClient01.class);
	private static String HOST = "127.0.0.1";
	private static int PORT = 8888;

	public static void main(String[] args) {
		// 创建一个非阻塞的客户端程序
		IoConnector connector = new NioSocketConnector();
		// 添加过滤器
		connector.getFilterChain().addLast("myChin",new ProtocolCodecFilter(new TextLineCodecFactory()));
		// 添加业务逻辑处理器类
		connector.setHandler(new Demo1ClientHandler());
		IoSession session = null;
		try {
			// 创建连接
			ConnectFuture future = connector.connect(new InetSocketAddress(HOST, PORT));
			// 等待连接创建完成
			future.awaitUninterruptibly();
			// 获得session
			session = future.getSession();
			// 发送消息
			session.write("接收成功");
		} catch (Exception e) {
			logger.error("客户端链接异常...", e);
		}
		session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
		connector.dispose();
	}
}

   逻辑处理器

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

public class Demo1ClientHandler extends IoHandlerAdapter {
	private static Logger logger = Logger.getLogger(Demo1ClientHandler.class);

	//当一个客端端连结进入时
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("客户端"+session.getRemoteAddress()+"连接成功");
		session.write("我来啦........");
	}
	//当一个客户端关闭时
	@Override
	public void sessionClosed(IoSession session) {
		logger.info("一个客户端断开连接");
	}
	//当客户端发送的消息到达时
	@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);
	}
}

 6,总结:

    服务端程序或客户端程序创建过程:

    创建连接--->添加消息过滤器(编码解码等) --->添加业务处理

 

    Mina 的三个核心接口:IoService 接口,IoFilter 接口和 IoHandler 接口:
        ●  第一步. 创建服务对象(客户端或服务端) ---IoService 接口实现
        ● 第二步. 数据过滤(编码解码等) ---IOFilter 接口实现
        ●  第三步. 业务处理 ---IoHandler 接口实现

 

 

你可能感兴趣的:(java,apache,框架,socket,Mina)