使用Apache MINA框架搭建服务端

open代码123 10年前

使用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);            }                }