Android--Netty的理解和使用

/ AndroidJava / 没有评论 / 2172浏览

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但性能非常高)


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()
                //5s未发送数据,回调userEventTriggered
                .addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS))
                .addLast(new LineBasedFrameDecoder(1024))
                .addLast(new StringDecoder(CharsetUtil.UTF_8))
                .addLast(new StringEncoder(CharsetUtil.UTF_8))
                .addLast(new TimeServerHandler())
                .addLast(new HeartbeatServerHandler())
                .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


相关链接: