Android--Netty的理解和使用

Netty的官方讲解:

*[The Netty project](http://netty.io/)* is an effort to provide an asynchronous event-driven network application framework and tooling for the rapid development of maintainable high-performance · high-scalability protocol servers and clients.

In other words, Netty is an NIO client server framework that enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server development.

'Quick and easy' does not mean that a resulting application will suffer from a maintainability or a performance issue. Netty has been designed carefully with the experiences earned from the implementation of a lot of protocols such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. As a result, Netty has succeeded to find a way to achieve ease of development, performance, stability, and flexibility without a compromise.

Some users might already have found other network application framework that claims to have the same advantage, and you might want to ask what makes Netty so different from them. The answer is the philosophy it is built on. Netty is designed to give you the most comfortable experience both in terms of the API and the implementation from the day one. It is not something tangible but you will realize that this philosophy will make your life much easier as you read this guide and play with Netty.

Netty是由JBOSS提供的一个java开源框架。Netty 是一个基于NIO的客户、服务器端编程框架,Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序dsf。

NIO:是一种同步非阻塞的I/O模型,也是I/O多路复用的基础,已经被越来越多地应用到大型应用服务器,成为解决高并发与大量连接、I/O处理问题的有效方式。
NIO一个重要的特点是:socket主要的读、写、注册和接收函数,在等待就绪阶段都是非阻塞的,真正的I/O操作是同步阻塞的(消耗CPU但性能非常高)
Java NIO浅析:https://mp.weixin.qq.com/s/HhwaXd8x7zONr8N1ojSnsQ?
Netty 能做什么: https://www.zhihu.com/question/24322387/answer/78947405


tinker的Mars框架和Netty框架类似, 但是Mars需要READ_PHONE_STATE等权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

如果您的App需要上传到google play store,您需要将READ_PHONE_STATE权限屏蔽掉或者移除,否则可能会被下架(欧盟数据保护条例)。


心跳检测机制:
1.继承SimpleChannelInboundHandler,当客户端的所有ChannelHandler中指定时间内没有write事件,则会触发userEventTriggered方法(心跳超时事件)

    //利用写空闲发送心跳检测消息
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
            // TODO: 2018/6/13   
            //ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);                   
            }            
    }

//连接成功触发channelActive
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        listener.onStateChanged(NettyListener.STATE_CONNECT_SUCCESS);
    }
//断开连接触发channelInactive
   @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // TODO: 2018/6/13 重连操作 
    }
//客户端收到消息
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String byteBuf) throws Exception {
   //通过接口将值传出去
        listener.onMessageRes(byteBuf);
    }
//异常回调,默认的exceptionCaught只会打出日志,不会关掉channel
   @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        listener.onStateChanged(NettyListener.STATE_CONNECT_ERROR);
        cause.printStackTrace();
        ctx.close();
    }

2.实现ChannelInboundHandlerAdapter

import java.util.Date;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {
    private ByteBuf buf;
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        buf = ctx.alloc().buffer(4); // (1)
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        buf.release(); // (1)
        buf = null;
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf m = (ByteBuf) msg;
        buf.writeBytes(m); // (2)
        m.release();
        
        if (buf.readableBytes() >= 4) { // (3)
       
            ctx.close();
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

3.创建EventLoopGroup线程组和Bootstrap(Bootstrap 是 Netty 提供的一个便利的工厂类,通过Bootstrap 来完成 Netty 的客户端或服务器端的 Netty 初始化.)

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap().group(group)
                        //禁用nagle算法 Nagle算法就是为了尽可能发送大块数据,避免网络中充斥着许多小数据块。
                        .option(ChannelOption.TCP_NODELAY, true)//屏蔽Nagle算法试图
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                        //指定NIO方式   //指定是NioSocketChannel, 用NioSctpChannel会抛异常
                        .channel(NioSocketChannel.class)
                        //指定编解码器,处理数据的Handler
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));//5s未发送数据,回调userEventTriggered
                                socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                                socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                                socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                                socketChannel.pipeline().addLast(new TimeServerHandler());
                                socketChannel.pipeline().addLast(new HeartbeatServerHandler());
                                socketChannel.pipeline().addLast(new NettyClientHandler(nettyListener));
//                                Packet packet = Packet.newInstance();
//                                byte[] bytes = packet.packetHeader(20, 0x100, (short) 200, (short) 0, (short) 1, 1, 0);
                            }
                        });

4.连接服务器的host和port

     channelFuture = bootstrap.connect(host,tcp_port).addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
                            if (channelFuture.isSuccess()) {
                               //连接成功
                                channel = channelFuture.channel();
                            } else {
                                //连接失败
                            }
                        }
                    }).sync();
                    channelFuture.channel().closeFuture().sync();
                    Log.e(TAG, " 断开连接");

5.连接成功后,向服务器发送信息

channel.writeAndFlush("你要发送的信息").addListener(listener);

6.断开关闭连接

if (null != channelFuture) {
    if (channelFuture.channel() != null && channelFuture.channel().isOpen()) {
        channelFuture.channel().close();
    }
}
group.shutdownGracefully();

7.Channel使用完毕后,一定要调用close(),释放通道占用的资源。
8.结合Service保活,实现Socket长连接
《Android应用进程防杀死》: https://www.jianshu.com/p/22a708c74c1e


相关链接:
jar下载地址:http://netty.io/downloads.html
netty官方地址: http://netty.io/
netty4.x 官方地址:http://netty.io/wiki/user-guide-for-4.x.html
Netty 实现聊天功能:https://waylau.com/netty-chat/
netty实现长连接心跳检: https://blog.csdn.net/qq_19983129/article/details/53025732

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Netty的简单介绍 Netty 是一个 NIO client-server(客户端服务器)框架,使用 Netty...
    AI乔治阅读 8,459评论 1 101
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Netty是一个高性能、异步事件驱动的NIO框架,它提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架...
    认真期待阅读 2,794评论 1 27
  • 我要说的聂人是这样一群人:他们的耳朵与身同高,走路的时候,把它捏在手里,缠在腰间,或者扎成一束披在衣背上。他们厌倦...
    尺八_阅读 1,100评论 4 10
  • 我总算还是明白,如花美眷,终抵不过似水流年。姹紫嫣红的春色,也只是韶光一现。其实我们都会有被岁月老去红颜的那一天。...
    才下眉头却上心头xhj阅读 268评论 0 0