我是靠谱客的博主 精明大白,最近开发中收集的这篇文章主要介绍Android使用mina传输数据以及发送心跳,有重连机制,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在实验室写项目时,需要使用tcp的连接以及发送心跳给后台,还需接收后台给的数据,还可以给后台发送数据

1、先去写了很多的后台发送数据来我们去编解码

public class ByteArrayCodecFactory implements ProtocolCodecFactory {
    private ByteArrayDecoder decoder;
    private ByteArrayEncoder encoder;

    public ByteArrayCodecFactory() {
        encoder = new ByteArrayEncoder();
        decoder = new ByteArrayDecoder();
    }

    @Override
    public ProtocolDecoder getDecoder(IoSession session) throws Exception {
        return decoder;
    }

    @Override
    public ProtocolEncoder getEncoder(IoSession session) throws Exception {
        return encoder;
    }

    //编码
    public class ByteArrayEncoder extends ProtocolEncoderAdapter {

        @Override
        public void encode(IoSession session, Object message, ProtocolEncoderOutput out) {
            out.write(message);
            Log.d("check send", "encode: "+message.toString());
            out.flush();
        }
    }

    private final static Charset charset = Charset.forName("UTF-8");
    // 可变的IoBuffer数据缓冲区
    private IoBuffer buff = IoBuffer.allocate(100).setAutoExpand(true);

    //解码
    public class ByteArrayDecoder extends ProtocolDecoderAdapter {
            @Override
            public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
                    throws Exception {

                while (in.hasRemaining()) {
                    byte b = in.get();
                    switch (b){
                        case 'n':
                            buff.flip();
                            byte[] bytes = new byte[buff.limit()];
                            buff.get(bytes);
                            Log.e("+++++++解码器打印+++++++:" ,new String(bytes));
                            out.write(bytes);
                            buff.clear();
                            break;
                        default:
                            buff.put(b);
                    }
                }
            }
    }

}

2、写了去捕获后台给我们发送到的数据

@Override
public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {

    System.out.println("捕获客户端发送信息异常....:" + arg0.getId() + ";Throwable:" + arg1.getMessage());
}

@Override
public void inputClosed(IoSession arg0) throws Exception {
    arg0.closeNow();    // 不发心跳时:加上该句。有心跳时可以不用加。
}

3、写了发送心跳包的方法

@Override
public boolean isRequest(IoSession session, Object message) {
    //如果是服务器发送过来的心跳包, return true后会在 getResponse() 方法中处理心跳包.

    if (message instanceof IoBuffer) {
        iobuffermessage = (IoBuffer) message;
        b = new byte[iobuffermessage.limit()];
        iobuffermessage.get(b);
        if (iobuffermessage.remaining() == iobuffermessage.limit()) {
            b = new byte[iobuffermessage.limit()];
            iobuffermessage.get(b);
        }
        if (new String(b) == minaConfig.getHeartone()) {
            return true;
        }
    }
    else if (message instanceof byte[] && new String((byte[]) message).equals(minaConfig.getHeartone())) {
        return true;
    }
    return false;
}

/**
 * 判断是否是心跳响应包,不管是对方的,还是自己的
 */
@Override
public boolean isResponse(IoSession session, Object message) {
    //如果是客户端主动向服务器发起的心跳包, return true, 该框架会发送 getRequest() 方法返回的心跳包内容.
    if (message instanceof IoBuffer) {
        iobuffermessage = (IoBuffer) message;
        if (iobuffermessage.remaining() == iobuffermessage.limit()) {
            b = new byte[iobuffermessage.limit()];
            iobuffermessage.get(b);
        }
        if (new String(b) == minaConfig.getHearttwo()) {

            return true;
        }
        return true;


    } else if (message instanceof byte[] && new String((byte[]) message).equals(minaConfig.getHearttwo())) {
        return true;
    }

    return false;


}

4、开始去创建连接

rivate boolean createConnect() {
        if (nioSocketConnector == null) {
            nioSocketConnector = new NioSocketConnector();
        } else {
            nioSocketConnector.dispose();// 关闭原有的连接器
            nioSocketConnector = new NioSocketConnector();

        }
        if (keepAliveFilter == null) {
            keepAliveFilter = new KeepAliveFilter(new MinaKeepAliveFilter(minaConfig), IdleStatus.BOTH_IDLE, KeepAliveRequestTimeoutHandler.DEAF_SPEAKER);
            /*
             * IdleStatus参数为 READER_IDLE
             * ,及表明如果当前连接的读通道空闲的时候在指定的时间间隔getRequestInterval后发送出心跳请求,以及发出Idle事件。
             * KeepAliveRequestTimeoutHandler设置为CLOS表明, 当发出的心跳请求在规定时间内没有接受到反馈的时候则调用CLOSE方式关闭连接
             * KeepAliveRequestTimeoutHandler设置为DEAF_SPEAKER表明,不需要发心跳
             */
//            keepAliveFilter.setForwardEvent(true);// 继续调用 IoHandlerAdapter 中的 sessionIdle时间
//            keepAliveFilter.setRequestInterval(minaConfig.getHeartsendTime());// 设置心跳发送时间间隔/s
//            keepAliveFilter.setRequestTimeout(minaConfig.getHeartTimeout());// 设置心跳判断的超时时间/s
//            keepAliveFilter.setRequestTimeoutHandler(new MinaKeepAliveRequestTimeoutHandler());// 设置超时的逻辑处理类
        }
        try {
            isconnect = false;
            nioSocketConnector = new NioSocketConnector();
            nioSocketConnector.setConnectTimeoutMillis(minaConfig.getConnectTimeout());// 设置连接超时时间/ms
            nioSocketConnector.getSessionConfig().setReadBufferSize(minaConfig.getReadbufferSize());// 设置接收缓冲区大小/b
            loggingFilter = new LoggingFilter();
            loggingFilter.setExceptionCaughtLogLevel(LogLevel.DEBUG);
            loggingFilter.setMessageReceivedLogLevel(LogLevel.DEBUG);
            loggingFilter.setMessageSentLogLevel(LogLevel.DEBUG);
            loggingFilter.setSessionClosedLogLevel(LogLevel.DEBUG);
            loggingFilter.setSessionCreatedLogLevel(LogLevel.DEBUG);
            loggingFilter .setSessionIdleLogLevel(LogLevel.DEBUG);
            loggingFilter. setSessionOpenedLogLevel(LogLevel.DEBUG);
            nioSocketConnector.getFilterChain().addFirst("logger", loggingFilter);
            nioSocketConnector.getFilterChain().addFirst("codec", new ProtocolCodecFilter(new ByteArrayCodecFactory()));//添加字符过滤器
            nioSocketConnector.getFilterChain().addLast("keepalive", keepAliveFilter);
            nioSocketConnector.setHandler(new MinaClientHandler(minaConfig.getiReceived(), this));// 消息处理
//            nioSocketConnector.addListener(new MinaServiceListener());//服务监听
            connectFuture = nioSocketConnector.connect(new InetSocketAddress(minaConfig.getHost(), minaConfig.getPort()));// 创建连接
            connectFuture.awaitUninterruptibly();// 等待连接
            ioSession = connectFuture.getSession();
            isconnect = true;
            System.out.println("连接成功!");
        } catch (Exception e) {
            e.printStackTrace();
            isconnect = false;
        }
        return isconnect;
    }

    /**
     * 连接
     */
    public void connect() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                int i = 1;
                System.out.println("Thread:" + Thread.currentThread().getName());
                while (!createConnect()) {
                    System.out.println("正在尝试第" + i + "次连接...");
                    try {
                        Thread.sleep(2000);
                        i++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                checkQueue();
            }
        }.start();
    }

在这里就是连接没有建立上,一直陷入死循环,直到连接成功

5、开始进行连接

 IReceived iReceived = new IReceived() {
                        @Override
                        public void received(String str) {
                            Log.e("接收的数据", str);
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(str);
                                String getResponse = jsonObject.getString("response");

                                if (jsonObject.getString("cmd").equals("imgRequest")) {
                                        Thread.sleep(1000);
                                        minaManager.send1(sendManager());

                                } else {

                                }
                            } catch (Exception e) {
                                Log.e("HomeActivity", "主界面接收数据,类型转换错误");
                            }
                        }
                    };
//                    Log.e("接收的数据", "2222222222222");
                    MinaConfig minaConfig = new MinaConfig.Builder()
                       //     .heartone_heartwo(JSON.toJSONString(map2), JSON.toJSONString(map))    去掉心跳
                            .host(RetrofitHelper.getIP(), RetrofitHelper.getMinaPort())
                            .iReceived(iReceived)
                            .create();
                    minaManager = MinaManager.getInstence(minaConfig);
                    minaManager.connect();

最后

以上就是精明大白为你收集整理的Android使用mina传输数据以及发送心跳,有重连机制的全部内容,希望文章能够帮你解决Android使用mina传输数据以及发送心跳,有重连机制所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部