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應用進程防殺死》: http://www.lxweimin.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