Mina长连接Android使用

首先使用mina,先自己简单的搭建起来一个demo,客户端和服务器端先能正常发送消息,这样才能完成后续操作,需要注意是,在android客户端和服务器端进行中文数据传递的时候,需要编码 URLEncoder 和 解码 URLDecoder来进行数据的编码和解码操作,否则无法传递中文数据,并且客户端和服务器端使用的jar包最好保持一致,避免发生一些未知的错误。

Android客户端核心代码:

        mConnection = new NioSocketConnector();
        //设置链接超时时间
        mConnection.setConnectTimeoutMillis(30000);
        //设置过滤链
        mConnection.getFilterChain().addLast("logging", new LoggingFilter());
        //添加过滤器
        mConnection.getFilterChain().addLast("codec", new ProtocolCodecFilter(new      TextLineCodecFactory(Charset.forName("UTF-8"))));
        //设置业务处理类,handler
        mConnection.setHandler(new DefaultHandler(mContext.get()));


            ConnectFuture future = mConnection.connect(new    InetSocketAddress(mConfig.getIp(),mConfig.getPort()));//创建链接
            future.awaitUninterruptibly();// 等待连接创建完成
            mSession = future.getSession();//获得session
            Log.e(TAG,"future.getSession() :"+mSession);
            mSession.write("start");
            mSession.getCloseFuture().awaitUninterruptibly();//等待连接断开

服务器端其实和客户端类似
tip:服务器端使用的对象是IoAcceptor ,但是Android端使用的是 NioSocketConnector

            IoAcceptor acceptor = new NioSocketAcceptor();  
            //日志过滤器 
           //acceptor.getFilterChain().addLast("logger", new LoggingFilter());  
            //进行指定格式
            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
            //处理类
            acceptor.setHandler(new MyServerHandler());  
            //设置缓存大小
            acceptor.getSessionConfig().setReadBufferSize(BUF_SIZE);  
            //10秒以后变为空闲状态
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  
            try {  
                //绑定端口号
                acceptor.bind(new InetSocketAddress(PORT));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  

保持长连接的主要思路,后台开启Android服务器,然后 收到消息以后,通过发送广播进行获取数据。具体事项看代码:
http://download.csdn.net/detail/chameleon_zhao/9706313

猜你喜欢

转载自blog.csdn.net/chameleon_zhao/article/details/53535467