一秒学会安卓tcp基于netty4.x心跳,断线重连,状态监听

从网上找了好多信息,基于安卓完整的tcp连接的各种处理没有完整的案例,基于业务开发,必须用到tcp,并需要稳定的连接,开发并做了大量的测试与优化工作,希望能帮到有同样需求的人!!!

好了,废话不多说,直接上代码!!

第一步:依赖netty-all-4.0.23.Final

第二步:初始化netty

  public NettyClientBootstrap(Context context, String[] actions, int port, String host) {
        this.actions = actions;
        this.context = context;
        this.port = port;
        this.host = host;
        //初始化连接
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1024, 1024 * 32, 1024 * 64));
        bootstrap.group(eventLoopGroup);
        bootstrap.remoteAddress(host, port);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new IdleStateHandler(20, 10, 0));
                socketChannel.pipeline().addLast( new NettyClientHandler());
            }
        });
    }

第三步:连接netty

/**
     * first init tcp connect
     */
    private ChannelFuture future = null;
    public void start() {
        LogUtil.printError("tcp", "connecing---------" + host + port);
        try {
            future = bootstrap.connect(new InetSocketAddress(host, port)).sync();
            if (future.isSuccess()) {
                socketChannel = (SocketChannel) future.channel();
                return;
            } else {
                LogUtil.printError("tcp", "TcpUnConnect------" + "future is unConnect");
            }
        } catch (Exception e) {
            LogUtil.printError("tcp", "TcpUnConnect------" + e.toString());
        }
      
    }

第四步:发送Tcp消息:

   /**
     * send tcp msg
     * @param msg
     */
    public void startNetty(final TCPData msg) {
        ThreadPoolProxy.getInstance(5, 5, 12 * 1000).executeTask(new Runnable() {
            @Override
            public void run() {
                if (isConnect) {
                    socketChannel.writeAndFlush(msg);
                }
            }
        });

    }


其他:关于Tcp监听部分代码:

 public class NettyClientHandler extends SimpleChannelInboundHandler<Object> {
        //利用写空闲发送心跳检测消息
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                switch (e.state()) {
                    case WRITER_IDLE:
                        
                }
            }
        }


        //这里是接受服务端发送过来的消息
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object baseMsg) throws Exception {
            String msgObj = (String) baseMsg;
        
        }


        //这里是断线要进行的操作
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
           
        }

        //这里是出现异常的话要进行的操作
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
           ;
        }

    }

其实通过以上部分基本上就已经可以完成大部分tcp处理

demo地址:http://download.csdn.net/detail/android_koukou/9887169

猜你喜欢

转载自blog.csdn.net/android_koukou/article/details/74173512