Netty简介
Netty是由JBOSS提供的一个java开源框架,现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。
也就是说,Netty 是一个基于NIO的客户、服务器端的编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户、服务端应用。Netty相当于简化和流线化了网络应用的编程开发过程,例如:基于TCP和UDP的socket服务开发。
“快速”和“简单”并不用产生维护性或性能上的问题。Netty 是一个吸收了多种协议(包括FTP、SMTP、HTTP等各种二进制文本协议)的实现经验,并经过相当精心设计的项目。最终,Netty 成功的找到了一种方式,在保证易于开发的同时还保证了其应用的性能,稳定性和伸缩性
简单来说Netty网络库提供了更简洁,更方便使用的NIO编程方式,并且提供了非常多有用且高效的API。使得我们网络编程更容易,方便。更具有框架性。
使用Netty实际上最最最重要的就是解决了JDK存在的epoll问题
在JDK的默认NIO中,Selector可能会产生空轮询,如此以来如果在开发过程中出现空轮询会让CPU直接占用率飙升到100%,这种内部BUG,我们没有办法进行调试。
下面我们就来简介Netty的组件以及基本框架的源代码
首先将依赖复制到maven项目中的pom.xml文件。
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.31.Final</version>
</dependency>
Netty AIO异步基本框架
首先我们先介绍Netty的几大组件
bootstrap:启动辅助类
EventLoopGroup:事件驱动线程池
Channel:管道
ChannelFuture:异步调用的管道结果
ChannelHandler:管道处理组件
ChannelPipeline:实现处理的管道
详细介绍:【死磕Netty】-----Netty的核心组件
基本框架思路:
与NIO的主从reactor一样,主Selector监听处理连接事件,从selector监听处理读写事件,处理需要单独的类去处理读写。也就是Handler。
而对应在Netty中,则是Bootstrap辅助启动类,辅助启动以及配置Netty,两个线程池EventLoop,分为主线程池(bossgroup)和从线程池,主线程池(workgroup)负责监听处理连接事件,从线程池负责处理读写事件,然而在Netty中,读事件和写事件不再是一个方法直接完成,而是分步骤去完成,也就是将一个方法进行解耦,使得操作更加灵活。
源代码:
服务端:
import JSON.TEST.zhb.server.ServerHandler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
public class NettyServer {
//port和三大组件
private final int port = 4313;
//启动辅助类
private ServerBootstrap serverBootstrap;
//主线程,主要监听以及处理连接事件
private EventLoopGroup bossGroup ;
//子线程,用于处理读事件和写事件
private EventLoopGroup workGroup;
//初始化组件
NettyServer(){
serverBootstrap = new ServerBootstrap();
//主线程处理监听事件所以可以少一些
bossGroup = new NioEventLoopGroup(10);
//子线程处理读写相对多一些
workGroup = new NioEventLoopGroup(20);
}
void serverStart(){
//首先利用启动辅助类将主线程和子线程进行绑定,以及对应的管道
serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class);
//绑定以后主线程异步自己调用
//子线程处理逻辑
//第一步,初始化 使用管道的初始化接口辅助
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//第二步按照处理逻辑的步骤添加到双链表中
socketChannel.pipeline().addLast(new NettyServerHandler());
}
});
try {
//由于此模型是AIO异步模型,所以什么时候开始连接,我们并不清楚,
//所以将它定义为一个未来的 future连接管道
ChannelFuture future = serverBootstrap.bind(port).sync();
//最后当前所有连接关闭,会自动异步调用此关闭方法
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//最后当连接关闭之后要关闭两个线程池
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
NettyServer nettyServer = new NettyServer();
nettyServer.serverStart();
}
}
服务端的handler:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//三种事件的处理
//连接事件
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//此时可处理可不处理,因为连接事件是主线程处理的。
//这里只是给了一个提示而已
System.out.println("已有客户端连接");
}
//读事件处理
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
//msg已经是数据了,不过必须转成ByteBuf,再设置字符集我们才可以看懂
ByteBuf buf = (ByteBuf) msg;
String rev = buf.toString(CharsetUtil.UTF_8);
System.out.println("client send : " + rev);
//回复消息
//1.将回复的内容准备
String sendMsg = "server recived !";
//2.将字符串转转为字节放到字符数组中
byte[] data = sendMsg.getBytes();
//3.将ByteBuf的大小设置为字符串的大小
ByteBuf byteBuf = Unpooled.buffer(data.length);
//4.把字节数组的内容装载到ByteBuf中
byteBuf.writeBytes(data);
//5..写入管道
ctx.writeAndFlush(byteBuf);
}finally {
//最后我们要将管道内的消息释放,以免影响下一条数据的读取
ReferenceCountUtil.release(msg);
}
}
//异常事件
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//发生异常暂时不处理,只打印。
cause.printStackTrace();
}
}
客户端:
import JSON.TEST.zhb.Client.ClientHandler.NettyClientHandler;
import JSON.TEST.zhb.server.NettyServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
private String ip = "127.0.0.1";
private int port = 4313;
//两个组件 bootstrap辅助启动类,以及工作线程池
private Bootstrap bootstrap;
//工作线程池,处理读写事件
private EventLoopGroup workGroup;
//初始化组件
NettyClient(){
bootstrap = new Bootstrap();
//因为客户端本身处理交互信息而言并不会非常的多,所以线程可以相对少一些
workGroup = new NioEventLoopGroup();
}
private void clientStart(){
//主线程也就是本线程,处理连接事件,workGroup处理读写事件
//首先将bootstrap启动类与线程池,以及对应的Channel管道进行绑定
//并且进行初始化
bootstrap.group(workGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//同样按顺序进行添加处理步骤中
socketChannel.pipeline().addLast(new NettyClientHandler());
}
});
try {
//连接的时刻我们不清楚,我么把它定义为一个未来连接的管道
ChannelFuture future = bootstrap.connect(ip, port).sync();
//当所有连接断开时,会异步调用此关闭方法
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//关闭线程池资源
workGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new NettyClient().clientStart();
}
}
客户端的handler:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import sun.nio.cs.UTF_32;
import java.util.Scanner;
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
//当连接完成时
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("已连接服务器");
String s = "Hello Sever";
byte[] data = s.getBytes();
ByteBuf byteBuf = Unpooled.buffer(data.length);
byteBuf.writeBytes(data);
ctx.writeAndFlush(byteBuf);
}
//处理读事件
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//将管道中的信息直接转为Bytebuf类型,然后设置字符集,我们就可以看懂信息了
ByteBuf buf = (ByteBuf)msg;
String rev = buf.toString(CharsetUtil.UTF_8);
System.out.println("server send :" + rev);
//写事件
System.out.println("请输入发送的消息: ");
Scanner scanner = new Scanner(System.in);
String sendMsg = scanner.nextLine();
//将消息先转为字节,然后放在ByteBuf中,然后放入管道。
byte[] datas = sendMsg.getBytes();
ByteBuf byteBuf = Unpooled.buffer(datas.length);
byteBuf.writeBytes(datas);
ctx.writeAndFlush(byteBuf);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//打印异常
cause.printStackTrace();
}
}