Android进阶之路Android开发经验谈Android技术知识

Netty在Android中使用

2019-11-06  本文已影响0人  浅吟且行的时光

引用netty介绍文档中的一句话:Netty适合用来开发高性能长连接的客户端或服务器
其次netty基于NIO,并做了封装与优化以及一些高级算法,使得使用起来相比原生NIO更加容易,性能更好

timg.jpg

1.使用方法

        //进行初始化
        NioEventLoopGroup  nioEventLoopGroup = new NioEventLoopGroup(); //初始化线程组
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class).group(nioEventLoopGroup);
        bootstrap.option(ChannelOption.TCP_NODELAY, true); //无阻塞
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true); //长连接
        bootstrap.option(ChannelOption.SO_TIMEOUT, SLEEP_TIME); //收发超时
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                        .addLast(new ByteArrayDecoder())  //接收解码方式
                        .addLast(new ByteArrayEncoder())  //发送编码方式
                        .addLast(new ChannelHandle(ConnectService.this)); //处理数据接收
            }
        });

//开始建立连接并监听返回
ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(AppInfo.serverIp, AppInfo.serverPort));
                channelFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) {
                        AppInfo.isConnected = future.isSuccess();
                        if (future.isSuccess()) {
                            Log.d(TAG, "connect success !");                 
                        } else {
                            Log.d(TAG, "connect failed !");   
                        }
                    }
                });
private void sendDataToServer(byte[] sendBytes) {
        if (sendBytes != null && sendBytes.length > 0) {
            if (channelFuture != null && channelFuture.channel().isActive()) {
                channelFuture.channel().writeAndFlush(sendBytes);
            }
        }
    }
public static class ChannelHandle extends SimpleChannelInboundHandler<SimpleProtocol> {

        private ConnectService connectService;

        public ChannelHandle(ConnectService connectService) {
            this.connectService = connectService;
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
            Log.e(TAG, "channelInactive 连接失败");
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            super.userEventTriggered(ctx, evt);
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
                if (idleStateEvent.state().equals(IdleState.WRITER_IDLE)) {
                    Log.d(TAG, "userEventTriggered write idle");
                    if (connectService == null){
                        return;
                    }
                }else if (idleStateEvent.state().equals(IdleState.READER_IDLE)){
                    Log.d(TAG, "userEventTriggered read idle");
                    ctx.channel().close();
                }
            }
        }
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, byte[] data) throws Exception {
            if (simpleProtocol == null){
                return;
            }
           //处理接收到的数据data
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            Log.i(TAG, "exceptionCaught");
            cause.printStackTrace();
            ctx.close();
        }
    }

2.常见问题处理及通信优化

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                        .addLast(new ByteArrayDecoder())  //接收解码方式
                        .addLast(new ByteArrayEncoder())  //发送编码方式
                        .addLast(new ChannelHandle(ConnectService.this)); //处理数据接收
                        .addLast(new IdleStateHandler(30, 10, 0))
            }
        });

在添加初始化.addLast(new ChannelHandle(ConnectService.this));的ChannelHandle 类中重写超时回调方法

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            super.userEventTriggered(ctx, evt);
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
                if (idleStateEvent.state().equals(IdleState.WRITER_IDLE)) {
                    //写超时,此时可以发送心跳数据给服务器
                    Log.d(TAG, "userEventTriggered write idle");
                    if (connectService == null){
                        return;
                    }
                }else if (idleStateEvent.state().equals(IdleState.READER_IDLE)){
                    //读超时,此时代表没有收到心跳返回可以关闭当前连接进行重连
                    Log.d(TAG, "userEventTriggered read idle");
                    ctx.channel().close();
                }
            }
        }
private void reConnect(){
if (channelFuture != null && channelFuture.channel() != null && channelFuture.channel().isActive()){
                        channelFuture.channel().close();//已经连接时先关闭当前连接,关闭时回调exceptionCaught进行重新连接
                    }else {
                        connect(); //当前未连接,直接连接即可
                    }
}

连接失败回调

@Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
            Log.e(TAG, "channelInactive 连接失败");      
            if (connectService != null) {
                connectService.connect(); //重新连接
            }
        }

连接错误回调

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            Log.i(TAG, "exceptionCaught");
            cause.printStackTrace();
            ctx.close();  //关闭连接后回调channelInactive会重新调用connectService.connect();
        }
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(5000, 5000, 8000)); //接收缓冲区 最小值太小时数据接收不全

出现问题的原因2:没有处理粘包拆包问题 解决方法:
添加包的接收处理:addLast(new SimpleProtocolDecoder()) 解包处理避免粘包的主要步骤是:1.解协议头 2.解包长 3.读指定的包长后返回

public class SimpleProtocolDecoder extends ByteToMessageDecoder{

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        if (buffer.readableBytes() >= SimpleProtocol.BASE_LENGTH){
            int beginReader;
            while (true){
                beginReader = buffer.readerIndex();
                buffer.markReaderIndex();
                if (buffer.readShort() == AppInfo.HEAD_TAG){
                    buffer.readByte();
                    break;
                }
                buffer.resetReaderIndex();
                buffer.readByte();
                if (buffer.readableBytes() < SimpleProtocol.BASE_LENGTH){
                    return;
                }
            }

            int length = MyUtil.shortToBig(buffer.readShort()) - SimpleProtocol.BASE_LENGTH;
            //buffer.readerIndex(beginReader);
            //Log.e("TAG","length:"+buffer.readableBytes());
            if (buffer.readableBytes() < length){
                buffer.readerIndex(beginReader);
                return;
            }
            //byte[] data = new byte[length];
            byte[] data = new byte[length + SimpleProtocol.BASE_LENGTH];
            int pos = buffer.readerIndex() - SimpleProtocol.BASE_LENGTH;
            if (pos < 0){
                return;
            }
            buffer.readerIndex(pos);
            buffer.readBytes(data);

            SimpleProtocol simpleProtocol = new SimpleProtocol((short) data.length,data);
            out.add(simpleProtocol);
        }
    }

}

3.注意细节

if (channelFuture != null && channelFutureListener != null){
                    channelFuture.removeListener(channelFutureListener);         
                    channelFuture.cancel(true);
                }

4.其他

上一篇下一篇

猜你喜欢

热点阅读