
Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件Netty 中 :
常见的方法
Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。
但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件
Netty 网络通信的组件,能够用于执行网络 I/O 操作。
通过 Channel 可获得当前网络连接的通道的状态
通过 Channel 可获得 网络连接的配置参数 (例如接收缓冲区大小)
Channel 提供异步的网络 I/O 操作(如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即返回,并且不保证在调用结束时所请求的 I/O 操作已完成
调用立即返回一个 ChannelFuture 实例,通过注册监听器到 ChannelFuture 上,可以 I/O 操作成功、失败或取消时回调通知调用方
支持关联 I/O 操作与对应的处理程序
不同协议、不同的阻塞类型的连接都有不同的 Channel 类型与之对应,常用的 Channel 类型:
- NioSocketChannel,异步的客户端 TCP Socket 连接。
- NioServerSocketChannel,异步的服务器端 TCP Socket 连接。
- NioDatagramChannel,异步的 UDP 连接。
- NioSctpChannel,异步的客户端 Sctp 连接。
- NioSctpServerChannel,异步的 Sctp 服务器端连接,这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。
ChannelPipeline 是一个重点:
ChannelPipeline 是一个 Handler 的集合
它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(也可以这样理解:
ChannelPipeline 是 保存 ChannelHandler 的 List,用于处理或拦截Channel 的入站事件和出站操作)
ChannelPipeline 实现了一种高级形式的拦截过滤器模式,使用户可以完全控制事件的处理方式,以及 Channel中各个的 ChannelHandler 如何相互交互
在 Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下
- channel能拿到他对应的channelPipeline
- channelPipeline也可以获取到对应的channel
- channelPipeline中包含一个个的ChannelHandlerContext的双向链表
- 每个ChannelHandlerContext(保存 Channel 相关的所有上下文信息)里面包含对应具体的channelHandler
常用方法
ChannelPipeline addFirst(ChannelHandler… handlers)
把一个业务处理类(handler)添加到链中的第一个位置
ChannelPipeline addLast(ChannelHandler… handlers)
把一个业务处理类(handler)添加到链中的最后一个位置
保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象
即 ChannelHandlerContext 中 包 含 一 个 具 体 的 事 件 处 理 器 ChannelHandler , 同 时ChannelHandlerContext 中也绑定了对应的 pipeline 和 Channel 的信息,方便对 ChannelHandler 进行调用.
常用方法
Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数。
ChannelOption 参数如下:
EventLoopGroup 是一组 EventLoop(就是对应线程) 的抽象,Netty 为了更好的利用多核 CPU 资源,一般会有多个 EventLoop同时工作,每个 EventLoop 维护着一个 Selector 实例。
EventLoopGroup 提供 next 接口,可以从组里面按照一定规则获取其中一个 EventLoop 来处理任务。
在 Netty服务器端编程中 ,我们一般 都 需 要 提 供 两 个 EventLoopGroup , 例 如 :
通常一个服务端口即一个 ServerSocketChannel 对应一个 Selector 和一个 EventLoop 线程。
服务端中,BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进行 IO 处理,如下图所示:↓
常用方法:
public NioEventLoopGroup(),构造方法
public Future> shutdownGracefully(),断开连接,关闭线程
Netty 提供一个专门用来操作缓冲区(即 Netty 的数据容器)的工具类
他内部维护了对应的readerIndex和writerIndex
相比NIO的ByteBuffer,Netty 提供的ByteBuf不用考虑flip反转去操作读写
常用方法如下所示
举例说明 Unpooled 获取 Netty 的数据容器 ByteBuf 的基本使用
案例1
public class NettyByteBuf01 {
public static void main(String[] args) {
//创建一个 ByteBuf
//说明
//1. 创建 对象,该对象包含一个数组 arr , 是一个 byte[10]
//2. 在 netty 的 buffer 中,不需要使用 flip 进行反转
// 底层维护了 readerindex 和 writerIndex
//3. 通过 readerindex 和 writerIndex 和 capacity, 将 buffer 分成三个区域
// 0---readerindex 已经读取的区域
// readerindex---writerIndex , 可读的区域
// writerIndex -- capacity, 可写的区域
ByteBuf buffer = Unpooled.buffer(10);
for(int i = 0; i < 10; i++) {
buffer.writeByte(i);
}
System.out.println("capacity=" + buffer.capacity());//10
//输出
// for(int i = 0; i
// System.out.println(buffer.getByte(i));
// }
for(int i = 0; i < buffer.capacity(); i++) {
System.out.println(buffer.readByte());
}
System.out.println("执行完毕");
}
}
案例 2
public class NettyByteBuf02 {
public static void main(String[] args) {
//创建 ByteBuf
ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
//使用相关的方法
if(byteBuf.hasArray()) { // true
byte[] content = byteBuf.array();
//将 content 转成字符串
System.out.println(new String(content, Charset.forName("utf-8")));
System.out.println("byteBuf=" + byteBuf);
System.out.println(byteBuf.arrayOffset()); // 0
System.out.println(byteBuf.readerIndex()); // 0
System.out.println(byteBuf.writerIndex()); // 12
System.out.println(byteBuf.capacity()); // 36
//System.out.println(byteBuf.readByte()); //
System.out.println(byteBuf.getByte(0)); // 104
int len = byteBuf.readableBytes(); //可读的字节数 12
System.out.println("len=" + len);
//使用 for 取出各个字节
for(int i = 0; i < len; i++) {
System.out.println((char) byteBuf.getByte(i));
}
//按照某个范围读取
System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8")));
System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8")));
}
}
}
- 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
- 实现多人群聊
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
- 目的:进一步理解 Netty 非阻塞网络编程机制
GroupChatServerHandler 服务端处理器
public class GroupChatServerHandler extends SimpleChannelInboundHandler{ //定义管理每个客户端的channel组 //GlobalEventExecutor.INSTANCE 全局的事件执行器,他是单例的 private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //当连接建立会第一个执行该方法,【客户端连接事件】 @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { //当客户端连接,第一时间将每个客户端的channel加入到channelGroup统一管理 Channel channel = ctx.channel(); //给当前channelGroup管理的所有channel的客户端都发送消息 channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + channel.remoteAddress() + "加入聊天室..."); channelGroup.add(channel); } //当某个channel处于活动状态,就会触发,用于发送某某上线【客户端上线活动状态事件】 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); System.out.println(sdf.format(new Date()) + "[客户端上线]:" + channel.remoteAddress() + "");//打印给服务端看 } //当某个channel离开状态,就会触发,用于发送某某下线【客户端离开非活动状态事件】 @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + ctx.channel().remoteAddress() + "离线了..."); } //当某个channel断开连接状态,就会触发【客户端离线断开连接事件】 @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { //告诉当前所有在线的用户,某某某断开连接 Channel channel = ctx.channel(); channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + channel.remoteAddress() + "离开聊天室..."); System.out.println("当前channel组的个数为:" + channelGroup.size()); } //客户端发送消息会触发【读取客户端数据事件】 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { //获取当前发送消息的用户 Channel nowSendChannel = ctx.channel(); //排除发送者自己,不给他转发消息 for (Channel channel : channelGroup) { if (!channel.equals(nowSendChannel)) { channel.writeAndFlush(sdf.format(new Date()) + "[客户_" + channel.remoteAddress() + "]发言:" + msg + "");//别的客户端 } else { channel.writeAndFlush(sdf.format(new Date()) + "[您自己发送的消息为]:" + msg + "");//发送者自己,回显消息给自己看 } } } //当发生异常会触发【异常触发事件】 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Channel channel = ctx.channel(); channel.close();//关闭通道 } }
GroupChatServer 服务端启动
public class GroupChatServer {
private final Integer port;//监听端口
private GroupChatServer (Integer port){
this.port=port;
}
public void run() throws InterruptedException {
//创建两个线程组
NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new ChannelInitializer() {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入处理器
pipeline.addLast("decoder",new StringDecoder());//解码器
//如果不加这个编码解码器的 无法直接传输字符串
pipeline.addLast("encoder",new StringEncoder());//编码器
pipeline.addLast("MyHandler",new GroupChatServerHandler());//自己的业务处理器
}
});
System.out.println("netty服务器启动成功.....绑定端口:"+port);
ChannelFuture cf = serverBootstrap.bind(port).sync();
cf.channel().closeFuture().sync();//监听关闭时间
}finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
//主入口
public static void main(String[] args) throws InterruptedException {
GroupChatServer server = new GroupChatServer(7000);
server.run();
}
}
GroupChatClientHandler 客户端处理器
public class GroupChatClientHandler extends SimpleChannelInboundHandler{ //读取服务端发来的消息【读写消息事件】 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { Channel channel = ctx.channel(); System.out.println("[用户_"+channel.remoteAddress()+"]发送的消息为:"+msg); } }
GroupChatClient 客户端启动
public class GroupChatClient {
private final String ipaddr;
private final int port;
private GroupChatClient(String ipaddr,int port) throws InterruptedException {
this.ipaddr = ipaddr;
this.port = port;
}
private void run() throws InterruptedException {
NioEventLoopGroup clientGroup = new NioEventLoopGroup();
try {
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(clientGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入处理器
pipeline.addLast("decoder",new StringDecoder());//解码器
//如果不加这个编码解码器的 无法直接传输字符串
pipeline.addLast("encoder",new StringEncoder());//编码器
pipeline.addLast("MyHandler",new GroupChatClientHandler());//加入自己的处理器
}
});
//监听连接是否成功
ChannelFuture cf = clientBootstrap.connect(ipaddr, port);
cf.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()){
System.out.println("连接成功....");
}else {
System.out.println("连接失败");
}
}
});
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
String msg = scanner.nextLine();
cf.channel().writeAndFlush(msg+"n");//发送消息
}
//对关闭通道进行监听
cf.channel().close().sync();
}finally {
clientGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
GroupChatClient client = new GroupChatClient("127.0.0.1", 7000);
client.run();
}
}
服务端
客户端1
客户端2
客户端3
- 编写一个 Netty 心跳检测机制案例, 当服务器超过 3 秒没有读时,就提示读空闲
- 当服务器超过 5 秒没有写操作时,就提示写空闲
- 实现当服务器超过 7 秒没有读或者写操作时,就提示读写空闲
MyHeartbeatServer
public class MyHeartbeatServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup boosGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))//netty自带的日志处理器
.childHandler(new ChannelInitializer() {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
pipeline.addLast(new HeartbeatHandler());//紧挨着上面的IdleStateHandler,作为下一个handler,这样子就可以触发到userEventTiggerd方法
}
});
System.out.println("服务端绑定端口7000.....启动成功");
//启动服务端
ChannelFuture cf = serverBootstrap.bind(7000).sync();
cf.channel().closeFuture().sync();
}finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
HeartbeatHandler
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent){
//evt向下转型
IdleStateEvent event = (IdleStateEvent)evt;
//判断是什么时间
switch (event.state()){
case ALL_IDLE:
System.out.println("【读写空闲】事件");
break;
case READER_IDLE:
System.out.println("【读空闲】事件");
break;
case WRITER_IDLE:
System.out.println("【写空闲】事件");
}
System.out.println(ctx.channel().remoteAddress()+"---客户端空闲时间发生---事件为【"+event.state()+"】");
//如果发生空闲事件后,就关闭channel,就会停止连接
// ctx.channel().close();
}
}
}
采用我们上面群聊案例的客户端连接
服务端
客户端
Http 协议是无状态的, 浏览器和服务器间的请求响应一次,下一次会重新创建连接.
要求:实现基于 webSocket 的长连接的全双工的交互
改变 Http 协议多次请求的约束,实现长连接了, 服务器可以发送消息给浏览器
客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知
运行界面
WebSocketServerFrameHandler自定义处理业务逻辑的处理器
public class WebSocketServerFrameHandler extends SimpleChannelInboundHandler{ protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { System.out.println("服务端收到消息:"+msg.text()); //回复浏览器 ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:"+ LocalDateTime.now()+""+msg.text())); } //客户端断开连接时会触发该事件 @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { //id.asLongText表示获取这channel唯一的值 System.out.println("handlerRemoved被调用:"+ctx.channel().id().asLongText()); } //客户端连接时会触发该事件 @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { //id.asLongText表示获取这channel唯一的值 System.out.println("handlerAdded被调用:"+ctx.channel().id().asLongText()); //id.asShortText表示获取这channel的值,这个不是唯一的。有可能重复 System.out.println("handlerAdded被调用:"+ctx.channel().id().asShortText()); } //当客户端发生异常时会触发该事件 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("异常发生:"+cause.getMessage()); ctx.channel().close(); } }
Websocket双工TCP长连接—服务端
public class WebSocketServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup boosGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))//netty自带的日志处理器
.childHandler(new ChannelInitializer() {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//基于http协议,使用http的编码和解码器
pipeline.addLast(new HttpServerCodec());
//是以 块方式 写,添加ChunkedWriteHandler处理器
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/achang"));
//自定义处理业务逻辑的处理器
pipeline.addLast(new WebSocketServerFrameHandler());
}
});
System.out.println("服务端绑定端口7000.....启动成功");
//启动服务端
ChannelFuture cf = serverBootstrap.bind(7000).sync();
cf.channel().closeFuture().sync();
}finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
前端的简单页面-achang.html
Title