1、Netty 是什么?
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
Netty 是 一个异步事件驱动的网络应用程序框架, 用于快速开发可维护的高性能协议服务器和客户端。
2、为什么使用Netty?
- 业务需要
- 统一了各类传输类型的API
- 拥有高吞吐量
- 低延迟
- 资源消耗少
- …
3、Netty 组成
- 核心组件:事件模型、缓冲区、各种类型的通信API
- 传输服务:NIO、EPOLL、OIO、本地、内嵌
- 协议:TCP/UDP/HTTP/HTTPS/SSL…
4、快速开始
1、 准备工作:客户端,服务端,客户端channel、服务端channel,引入netty依赖
2 、Netty Demo
添加Maven 依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.67.Final</version>
</dependency>
创建NettyServer服务启动类
public static void main(String[] args) {
// 接收连接
EventLoopGroup boss = new NioEventLoopGroup();
// 处理已经被接收的连接
EventLoopGroup worke = new NioEventLoopGroup();
int port = Integer.parseInt(args[0]);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
//设置EventLoopGroup
serverBootstrap.group(worke, boss)
// 指定channel类型;
.channel(NioServerSocketChannel.class)
//指定自定义的Handler
.childHandler(new NettyServerHander())
//设置channel的选项
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 绑定端口
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
System.out.println("server已启动,端口:" + port);
// 关闭服务
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worke.shutdownGracefully();
boss.shutdownGracefully();
}
}
创建服务接收channel:NettyServerHander类
// NettyServerHander 继承ChannelInboundHandlerAdapter
// 重新channelRead()方法
详细如下:
public class NettyServerHander extends ChannelInboundHandlerAdapter {
/**
* 从管道读取数据
* @param ctx
* @param msg
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println(ctx.channel().remoteAddress()+"service:"+msg);
//写消息到管道
ctx.channel();
// 刷新消息
ctx.writeAndFlush(msg);
}
/**
* 异常处理
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
cause.printStackTrace();
ctx.close();
}
}
创建客户端:NettyClient
// 设置EventLoopGroup
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(groop)
// 设置指定的channel类型
.channel(NioSocketChannel.class)
// 设置channel选项
.option(ChannelOption.TCP_NODELAY, true)
// 指定channel handle
.handler(new NettyClientHandler());
// 绑定端口
ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
此时客户端已经连接上了
// 获取channel
Channel channel = channelFuture.channel();
// 处理数据包括:处理数据格式类型使之符合要求
// 将数据写回到channel中
channel.writeAndFlush(buf);
// 关闭服务
channelFuture.channel().closeFuture().sync();
详细如下:
public static void main(String[] args) {
EventLoopGroup groop = new NioEventLoopGroup();
try {
String host = args[0];
int port = Integer.parseInt(args[1]);
Bootstrap bootstrap = new Bootstrap();
//设置EventLoopGroup
bootstrap.group(groop)
// 指定channel类型;
.channel(NioSocketChannel.class)
//设置channel的选项
.option(ChannelOption.TCP_NODELAY, true)
//指定自定义的Handler
.handler(new NettyClientHandler());
// 绑定端口
ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
System.out.println("client已连接,端口:" + port);
Channel channel = channelFuture.channel();
ByteBuffer write = ByteBuffer.allocate(32);
Reader in;
String out = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((out = reader.readLine())!=null){
write.put(out.getBytes(StandardCharsets.UTF_8));
write.flip();
write.rewind();
ByteBuf buf = Unpooled.copiedBuffer(write);
channel.writeAndFlush(buf);
// 清理缓冲区
write.clear();
}
// 关闭服务
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
groop.shutdownGracefully();
}
}
创建客户端接收channel:NettyClientHandler
// NettyClientHandler 继承 ChannelInboundHandlerAdapter
NettyClientHandler extends ChannelInboundHandlerAdapter
// 重新channelRead()方法
详细如下:
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 读取消息
ByteBuf buffer = (ByteBuf) msg;
String mg = buffer.toString(CharsetUtil.UTF_8);
System.out.println("client消息:"+mg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
5、测试
测试前客户端和服务端需要配置参数,且配置客户端参数要顺序一致不同的参数留空格,也可以直接将参数写在demo
参考:《Netty原理解析与开发实战》、Netty官网