前面学习了用Java原生NIO的编程实践,过程还是挺复杂的,需要熟练掌握Selector,ServerSocketChannel握,SocketChannel,ByteBuffer等。所以在绝大多数业务场景中我们可以使用Netty来进行NIO编程。先总结一下Netty的优点:
- API使用简单,开发门槛低
- 功能强大,预制了多种编解码功能,支持多种主流协议
- 定制能力强,可以通过ChannelHandler对通信框架进行灵活的扩展
- 性能高,成熟,稳定,社区活跃,版本迭代周期短
- 经历了大规模的商业应用考验,质量得到验证等
至于安装就不多说了,只要下载他的JAR包然后在普通java项目中导入就可以了。
编程实战
可以对比一下之前的原生NIO代码,是简洁了许多。
Netty服务端
package com.ph.Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* Create by PH on 2018/11/3
*/
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//采用默认值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一个线程组,包含了一组NIO线程,专门用于网络事件的处理,
//实际上他们就是Reactor线程组
//bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用于进行SocketChannel的网络读写
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服务端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel产生一个Channel用来接收连接,他的功能对应于JDK
// NIO类库中的ServerSocketChannel类。
.channel(NioServerSocketChannel.class)
//BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,
// 用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,
// Java将使用默认值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//绑定I/O事件处理类,作用类似于Reactor模式中的Handler类,主要用于处理网络I/O事件
.childHandler(new ChildChannelHandler());
//绑定端口,同步等待绑定操作完成,完成后返回一个ChannelFuture,用于异步操作的通知回调
ChannelFuture f = b.bind(port).sync();
//等待服务端监听端口关闭之后才退出main函数
f.channel().closeFuture().sync();
} finally {
//退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast(new ServerHandler());
}
}
}
/**
* ChannelInboundHandlerAdapter实现自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件处理方法可通过重写来自定义处理方式
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受客户端发送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//类似JDK中的ByteBuffer对象,不过它提供了更加强大和灵活的功能
ByteBuf buf = (ByteBuf) msg;
//通过readableBytes()方法获取缓冲区可读的字节数
byte[] req = new byte[buf.readableBytes()];
//将缓冲区中的字节数组复制到新建的byte数组中
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("Server receive: " + body);
//获得ByteBuf类型的数据
ByteBuf resp = Unpooled.copiedBuffer("Server message".getBytes());
//向客户端发送消息,不直接将消息写入SocketChannel中,只是把待发送的消息放到发送缓存数组中,
//再通过调用flush方法将缓冲区中的消息全部写到SocketChannel中
ctx.write(resp);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将消息发送队列中的消息写入到SocketChannel中发送给对方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//当发生异常时释放资源
ctx.close();
}
}
Netty客户端
package com.ph.Netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Create by PH on 2018/11/3
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//采用默认值
}
}
new NettyClient().connect(port, "127.0.0.1");
}
public void connect(int port, String host) throws Exception{
//配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast(new ClientHandler());
}
});
//发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客户端链路关闭
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private final ByteBuf msg;
public ClientHandler() {
byte[] req = "Client message".getBytes();
msg = Unpooled.buffer(req.length);
msg.writeBytes(req);
}
/**
* 当客户端和服务端TCP链路建立成功之后,Netty的NIO线程会调用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
//发送消息到服务端
ctx.writeAndFlush(msg);
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "utf-8");
System.out.println("Client receive :" + body);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}