1. 程式人生 > >使用Apache MINA框架搭建服務端

使用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("服務端與客戶端建立連線...");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logUtil.customLog("服務端與客戶端連線開啟...");
	}

	@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("服務端與客戶端連線關閉...");
		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);
	}

}