使用Apache MINA框架搭建服务端

Posted mthoutai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Apache MINA框架搭建服务端相关的知识,希望对你有一定的参考价值。

使用MINA框架搭建服务端步骤:

1、定义一个启动服务的类MinaServer,并实现接口ServletContextListener

2、定义一个处理业务逻辑的类MinaServerHandler,并继承类IoHandlerAdapter

类MinaServer代码例如以下:

import java.net.InetSocketAddress;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NiosocketAcceptor;

import com.utils.LogUtil;

public class MinaServer implements ServletContextListener, HttpSessionListener {
	private static NioSocketAcceptor acceptor;
	private static final int port = 9999;
	private static final LogUtil logUtil = LogUtil.getLogUtil(MinaServer.class);


	// 停止MINA服务
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			MinaServer.acceptor.unbind();
			MinaServer.acceptor.dispose();
			logUtil.customLog("Mina服务停止...");
		} catch (Exception e) {
			logUtil.customLog(e);
		}
	}

	// 启动MINA服务
	public void contextInitialized(ServletContextEvent sce) {
		try {
			// 创建一个非堵塞的server端的Socket
			acceptor = new NioSocketAcceptor();
			// 设置过滤器
			acceptor.getFilterChain().addLast(
					"serverCodec",
					new ProtocolCodecFilter(
							new ObjectSerializationCodecFactory()));
			acceptor.getFilterChain().addLast("ServerFilter",
					new ExecutorFilter());
			// 设置读取数据的缓冲区大小
			acceptor.getSessionConfig().setReadBufferSize(1024*102400);
			// 读写通道10秒内无操作进入空暇状态
			acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
			// 加入逻辑处理器
			acceptor.setHandler(new MinaServerHandler());
			// 绑定端口
			try {
				acceptor.bind(new InetSocketAddress(port));
			} catch (Exception e) {
			}
			logUtil.customLog("服务端启动成功...     端口号为:" + port);
		} catch (Exception e) {
			logUtil.customLog("服务端启动异常....");
		}

	}

	public void sessionCreated(HttpSessionEvent arg0) {
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
	}

}


MinaServerHandler代码例如以下:

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

import com.model.DeliverObject;
import com.model.Orders;
import com.model.Users;
import com.service.GoodsService;
import com.service.OrdersService;
import com.service.UserService;
import com.utils.GetBeanUtil;
import com.utils.LogUtil;
import com.utils.Params;

public class MinaServerHandler extends IoHandlerAdapter {

	private static final LogUtil logUtil = LogUtil
			.getLogUtil(MinaServerHandler.class);

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logUtil.customLog("服务端与client创建连接...");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logUtil.customLog("服务端与client连接打开...");
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		DeliverObject recvObj = (DeliverObject) message;
		int optionType = recvObj.getOptionType();
		// 假设是登录操作
		if (optionType == Params.LOGIN) {
			UserService userService = (UserService) GetBeanUtil
					.getBean("userService");
			userService.doLogin(session, (Users) recvObj.getObj());
		} else if (optionType == Params.REGISTER) {
			// 假设是注冊操作
			UserService userService = (UserService) GetBeanUtil
					.getBean("userService");
			userService.doRegister(session, (Users) recvObj.getObj());
		} else if (optionType == Params.UPDATEUSER) {
			// 假设是改动用户信息操作
			UserService userService = (UserService) GetBeanUtil
					.getBean("userService");
			userService.doUpdateUser(session, (Users) recvObj.getObj());
		} else if (optionType == Params.SEARCHGOODS) {
			// 假设是搜索商品操作
			GoodsService goodsService = (GoodsService) GetBeanUtil
					.getBean("goodsService");
			goodsService.doSearchGoods(session, (String) recvObj.getObj());
		} else if (optionType == Params.SUBMITORDERS) {
			// 假设是提交订单操作
			OrdersService ordersService = (OrdersService) GetBeanUtil
					.getBean("ordersService");
			ordersService.doSubmitOrders(session, (Orders) recvObj.getObj());
		} else if (optionType == Params.SEARCHALLORDERS) {
			// 假设是查询全部订单操作
			OrdersService ordersService = (OrdersService) GetBeanUtil
					.getBean("ordersService");
			ordersService.doSearchAllOrders(session, (Users) recvObj.getObj());
		}

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logUtil.customLog("服务端发送信息成功...");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logUtil.customLog("服务端与client连接关闭...");
		session.close(true);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		super.sessionIdle(session, status);
		logUtil.customLog("服务端进入空暇状态...");
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logUtil.customLog("服务端发送异常..." + cause);
		session.close(true);
	}

}








以上是关于使用Apache MINA框架搭建服务端的主要内容,如果未能解决你的问题,请参考以下文章

图解Apache Mina

Mina TCP服务端客户端 示例

用于传入文件的 Apache Mina SFTP 服务器端通道侦听器

使用mina 基于tcp协议实现客户端和服务端进行通信

spring+mybatis+mina+logback框架搭建

Netty与Mina