三大特性:并发高 传输快 封装好
BossGroup和WorkerGroup组成NioEventLoopGroupNioEventLoopGroup 是一个事件循环组,组中包含很多个事件循环NioEventLoop代表一个不断循环处理任务的线程每一个都有selector监听BossGroup 负责接收客户端的连接 WorkerGroup负责网络的读写BossGroup1) 轮询是否有accept事件发生2)处理事件,并且和客户端建立连接,NioSocketChannel -> SocketChannel -> Socket注册到workergroup中,使用seletor进行后续监听3)处理任务队列WorkerGroup1)轮询是否有read and write事件发生2) 找到 NioSocketChannel3)处理任务队列
Bootstrap对象
配置
group 指定一到两个事件循环组
channel 指定channel工厂 反射的方式创建channel使用
handler 指定处理器
childHandel 只在ServerBootstrap中使用 指定的是服务端所接收的客户端channel所使用的的处理器
option 指定的是TCP相关参数 以及netty自定义参数
配置参数的过程 称之为初始化
bind 将服务器的channel绑定到端口号 然后接收客户端连接 让整个netty运行起来
sync 因为绑定事件时异步的 所以sync同步等待结果 bind只触发了绑定端口的事件 需要使用sync等待事件执行的结果也就是知道运行起来
future.channel().closeFuture().sync(); 当通道被关闭时 才执行后续操作,sync使当前线程执行到此阻塞,以确保不执行后续的shutdown方法
HelloWord
服务端
//1.创建事件循环组 构建主从模型
//可以通过传参的方式定义事件循环组的大小 默认创建的线程数量 = CPU数量*2
//bossGroup 用来监听接收事件 workGroup 用来监听读写事件 是无限循环时间组(线程池)
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup();
//2.创建启动器
ServerBootstrap serverBootstrap = new ServerBootstrap();
//通过启动器设置相关参数 将事件循环组穿进去
//方法返回对象自身(ServerBootstrap) 提供了链式编程可以一直调用类下的方法
serverBootstrap.group(bossGroup, workGroup)
//声明当前使用的通道类型
// bio nio netty 层层封装
//ServerSocket--> ServerSocketChannel-->NioServerSocketChannel
.channel(NioServerSocketChannel.class)
//设置前面通道的处理器 使用netty提供的日志打印处理器
.handler(new LoggingHandler(LogLevel.INFO))
//设置客户端连接处理器
//此方法需要参数 ChannelInitializer通道初始化器
// 需要泛型SocketChannle客户端通道
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//实现抽象方法 初始化通道
//通过socketChannel获取管道 pipeline
//通道代表连接的角色 管道代表 处理业务逻辑的管理
//管道 相当于链表 将不同的处理器连接起来 管理的是处理器的顺序addLast()将处理器增加至尾部
socketChannel.pipeline().addLast(new NettyServerHandler());
//NettyServerHandler自定义的handler
}
});
System.out.println("======服务端初始化完成======");
try {
//启动并设置端口号 通过sync()异步启动
ChannelFuture future = serverBootstrap.bind(8888).sync();//阻塞直到连接完成
//将关闭通道的方式设置成异步的
// 阻塞finally中的代码执行
future.channel().closeFuture().sync();//阻塞 直到channel关闭
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//优雅的关闭
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
自定义服务端Handler
//自定义handler 的方式之一
// 继承 ChannelInboundHandlerAdaper
// 提供了在不同时期会触发的方法
@Shareable//标识同一个ChannelHandler的实例可以被多次添加到多个ChannelPipelines中,而且不会出现竞争条件
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//通道被启动--刚刚建立连接使用的方法
//业务使用中往往发生欢迎消息
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//ChannelHandlerContext 是通道处理器中的上下文
//包含了使用过程中的所需的参数 通道channel 管道pipeline 写数据等
System.out.println("channelActive 被触发看");
ctx.writeAndFlush("hell world netty");//写数据 可以直接写入字符串
}
//数据读取的方法
//当客户端发送消息时 读事件触发的方法
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//Object msg 就是传过来的消息数据
//netty的缓存区ByteBuf 是对ByteBuffer的封装
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println("客户端来自于:"+ctx.channel().remoteAddress());
//直接通过byteBuf中的toString方法进行输出 通过CharesetUtil设置编码格式
System.out.println("客户端传过来的消息:"+byteBuf.toString(CharsetUtil.UTF_8));
}
//数据读取完成 触发的方法
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//数据处理还是使用ByteBuf Unpooled是提供 在ByteBuf和String直接转换的方法
// Unpooled.copiedBuffer("",CharsetUtil.UTF_8)可以直接把字符串转成ByteBuf
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello client,干嘛那",CharsetUtil.UTF_8));
}
}
客户端
//客户端只需要一个事件循环组就可以了
EventLoopGroup group = new NioEventLoopGroup();
//客户端的启动器叫Bootstrap
Bootstrap bootstrap = new Bootstrap();
//启动器设置相关参数
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyClientHander());
}
});
try {
ChannelFuture sync = bootstrap.connect("127.0.0.1", 8888).sync();
sync.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
自定义客户端处理器
//自定义处理器
public class NettyClientHander extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client 成功建立");
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server ip为:"+ctx.channel().remoteAddress(), CharsetUtil.UTF_8));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println("服务端说:"+byteBuf.toString(CharsetUtil.UTF_8)+"IP:"+ctx.channel().remoteAddress());
}
}
String解码器和编码器
ChannelInitializer类中的channelInit方法中设置
ChannelPipeline pipeline = socketChannel.pipeline();
//添加自定义分隔符解码器 参数1 大小 2 是分隔符发送的消息都必须包含\r\n
pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()));
//添加String相关解码器
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
//添加String相关编码器
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
//加入自定义处理器
pipeline.addLast(new ChatClientHandler());
自定义处理器方式
继承ChannelInboundHandlerAdapter
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//通道被启动--刚刚建立连接使用的方法
//业务使用中往往发生欢迎消息
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
//数据读取的方法
//当客户端发送消息时 读事件触发的方法
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
}
//数据读取完成 触发的方法
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
}
继承SimpleChannelInboundHandler
//自定义处理器实现方式继承 SimpleChannelInboundHandler
//是ChannelInboundHandlerApadter的子类在父类的基础上封装了channelRead0方法
public class ChatServerHandler extends SimpleChannelInboundHandler {
//当多个通道传入handlder 使用通道组的管理方式
//ChannelGroup本质上是一个Set集合可直接遍历 key就是是=每一个channel
// GlobalEventExecutor.INSTANCE 全局事件执行器 单例
private static ChannelGroup channelGroup = new
DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
//刚刚建立连接是 执行的方法
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//将通道加入到通道事件组中
channelGroup.add(ctx.channel());
}
//当连接被移除或者断开 最后执行的方法
//自动将channel从channel组中移除
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {}
//读数据
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {}
//连接成功 此时通道是活跃的 channelActive在handlerAdded之后执行
public void channelActive(ChannelHandlerContext ctx) throws Exception {}
//通道不活跃的方法 处理用户下线的业务逻辑 会在handlerRemoved方法之前执行
public void channelInactive(ChannelHandlerContext ctx) throws Exception {}
//通用的异常处理方法
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
//关闭上下文 关闭通道 出现异常就关闭
ctx.close();
}
}
继承ChannelDuplexHandler
既可以处理入栈数据又可以处理处置数据
public class RedisClientHandler extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//读到数据的处理
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
//写数据处理
}
}
Http连接
Http相关的编码器与解码器
//服务端相关的解码器和编码器
HTTP在服务端需要将请求进行解码在将响应进行编码 HttpRequestDecoder和HttpResponseEncoder可以直接使用HttpServerCodec代替,自动进行请求解码在将响应编码 服务端传出去的消息可能比较大需要进行压缩通过添加压缩器HttpContentCompressor,由于HTTP是流式传输不是一次传输过去的 通过HttpObjectAggregator聚合器将数据整合成完整的消息 会将完整的请求或响应封装成FullHttpRequest类 和 FullHttpResponse类
//添加http请求解码器 服务端
pipeline.addLast(new HttpRequestDecoder());
//添加http响应编码器 服务端
pipeline.addLast(new HttpResponseEncoder());
// HttpServerCodec=HttpRequestDecoder+HttpResponseEncoder可以直接使用它
pipeline.addLast(new HttpServerCodec());
//添加http压缩器 用于服务端
pipeline.addLast(new HttpContentCompressor());
//添加http聚合器 http的请求和响应可能由很多部分组成需要聚合成一个完整的消息 //参数 可以出了的最大值
pipeline.addLast(new HttpObjectAggregator(512*1024));
由于聚合器聚合出完整的请求或响应包会自动封装成FullHttpRequest类 和 FullHttpResponse类
//客户端相关的解码器和编码器
Http在客户端需要将响应进行解码再将请求进行编码HttpResponseDecoder和HttpRequestEncoder可以直接使用HttpClientCodec代替,自动进行响应解码和请求编码 由于从服务端传过来的消息经过压缩通过解压缩器HttpContentDecompressor进行解压缩
//添加http响应解码器 用于客户端
pipeline.addLast(new HttpResponseDecoder());
//添加http请求编码器 用于客户端
pipeline.addLast(new HttpRequestEncoder());
//HttpClientCodec=HttpResponseDecoder+HttpRequestEncoder 可以直接使用 代替响应解和请求编
pipeline.addLast(new HttpClientCodec());
//添加http解压缩器 用于 客户端
pipeline.addLast(new HttpContentDecompressor());
模拟Http响应
//自定义Handler中代码
//ChannelInitializer 设置HttpServerCodec HttpContentCompressor HttpObjectAggregator
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
//默认的完整的http响应
//参数1:设置版本
//参数2:设置状态
//参数3:设置内容
//Unpooled.wrappedBuffer 可以将字符串转成字节直接写入Unpooled.copiedBuffer需要设置字符串且设置字符集
DefaultFullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer("hello http netty demo".getBytes())
);
//设置响应头
//设置请求/响应字段时可以通过HttpHeaderNames获取对应的字段
//通过HttpHeaderValues获取对应设置的值
HttpHeaders httpHeaders = response.headers();
//设置文本类型 contentType:text/plain
httpHeaders.add(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.TEXT_PLAIN+"charset=UTF-8");
//设置长度 //contentLength:response.content().readableBytes()获取设置内容的长度
//readableBytes可读的字节
httpHeaders.add(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
ctx.write(response);
}
//读完成之后刷新
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
WebSocket连接
websocket是由浏览器发起的
http协议标识符:http://127.0.0.1:8080
websocket协议标识符:ws://127.0.0.1:8080
websocket实现的原理:
通过http协议建立连接(握手和回答) 建立连接后不再使用http,而tcp自身支持双向通信的,所以可以达到“全双工”的效果
通信使用的是单位叫帧 frame TextWebSocketFrame //通过文本信息帧操作
客户端发送时会把消息切割成多个帧 服务端接收时将关联的多个帧组装起来
Websocket使用到的新处理器
//添加块方式写的处理器 用于较大数据
pipeline.addLast(new ChunkedWriteHandler());
//添加websocket请求路径处理器
// 参数是路径 ws:127.0.0.1:8888/hello
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
WebSocketDemo
websocket客户端的方法
onopen 连接建立时触发 才可通过send()方法发送消息
onmessage 接收服务端消息时触发
onerror 发送错误时触发
onclose 连接关闭时触发
WebSocket使用
1. var ws = new WebSocket("ws://127.0.0.1:7777/hello");//与服务端设置的请求路径处理器一直
2. ws.onopen=function(ev){//连接成功后
ws.send("设置发送的消息")
}
服务端
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boosGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
//设置等待队列的最大值
.option(ChannelOption.SO_BACKLOG, 128)
//设置设置连接为保持为活动的状态
.option(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new WebSocketInitializer());
try {
ChannelFuture future = bootstrap.bind(8888).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
ChannelInitializer
public class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//添加请求解码器和响应编码器
pipeline.addLast(new HttpServerCodec());
//添加块方式写的处理器 用于较大数据
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpContentCompressor());
pipeline.addLast(new HttpObjectAggregator(512*1024));
//添加websocket请求路径处理器
// 参数是路径 ws:127.0.0.1:8888/hello
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
pipeline.addLast(new WebSocketHandler());
}
自定义Handler
//泛型代表的是处理数据的单位 websocket处理的单位是帧
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
System.out.println(textWebSocketFrame.text());
Channel channel = ctx.channel();
//设置一个响应文本信息帧
TextWebSocketFrame socketFrame = new TextWebSocketFrame("hello client");
//写过去
channel.writeAndFlush(socketFrame);
}
}
客户端
<body>
<!--防止表单自动提交-->
<form onsubmit="return false">
<textarea id="message" style="height: 400px;width: 400px"></textarea>
<input id="send" type="button" value="发送"/>
<textarea id="resTest" style="height: 400px;width: 400px"></textarea>
</form>
<script>
const tem = document.getElementById("resTest");
const message = document.getElementById("message");
const send = document.getElementById("send");
var socket;
//判断当前浏览器是否支持websocket
if (!window.WebSocket){
alert("浏览器不支持websocket")
}
socket = new WebSocket("ws://127.0.0.1:8888/hello");
//设置开启连接的方法
socket.onopen=function (ev){
tem.value="连接已开启";
}
//接收数据的方法
socket.onmessage=function (ev){
tem.value=tem.value+"\n"+ev.data;
}
//设置关闭连接的方式
socket.onclose=function (ev) {
tem.value=tem.value+"\n"+"连接已关闭";
}
send.onclick=function (){
//判断是否有存在连接
if (!window.socket) return;
//判断socket当前状态
//4中状态 CONNECTION 真正连接 OPEN 已连接 CLOSING 正在关闭 CLOSED 已经关闭
//只有OPEN才可以发送数据
if (socket.readyState == WebSocket.OPEN){
socket.send(message.value);
}else {
alert("连接未开启")
}
}
</script>
</body>
心跳检测
服务端通过检测机制,验证客户端的活跃机制,验证客户端的活跃状态 不活跃则关闭
实现 通过在向pipeline中添加IdleStateHandler处理器
存在的状态:readerIdleTime 超过多长时间没有读
writerIdleTime 超过多长时间没有写
allIdleTime 超过多长时间没有读和写
心跳检查服务端代码
public class IdleServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
//参数 读空闲的超时时间 写空闲的超时时间 读写空闲的超时时间 时间单位(TimeUnit.SECONDS秒)
pipeline.addLast(new IdleStateHandler(5,10,20, TimeUnit.SECONDS));
//发现有空闲时 会触发idleStateEvent时间
//会推送给自定义handler的指定方法 userEventTriggered 进行时间操作
pipeline.addLast(new IdleServerHandler());
}
public class IdleServerHandler extends SimpleChannelInboundHandler<String> {
private int times = 0;
//读事件触发 处理的方法
@Override
protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
///当读到内容为 I am alive 字符串 进行写事件
if ("I am alive".equals(s)) {
ctx.writeAndFlush(Unpooled.copiedBuffer("收到", CharsetUtil.UTF_8));
}
}
//处理心跳检查事件的方法
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//Object就是事件 通过事件判断当前是读空闲 写空闲 还是读写空闲
IdleStateEvent event = (IdleStateEvent) evt;
String eventDexc = null;
switch (event.state()) {
case READER_IDLE:
eventDexc = "读空闲";
break;
case WRITER_IDLE:
eventDexc = "写空闲";
break;
case ALL_IDLE:
eventDexc = "读写都空闲";
break;
}
// 规定出现一次空闲就+1当出现3次就关闭客户端连接
System.out.println(ctx.channel().remoteAddress() + "发送超时时间" + eventDexc);
times++;
if (times > 3) {
System.out.println("空闲次数超过3次 关闭连接");
ctx.writeAndFlush("我即将要关闭");
ctx.channel().close();
}
}
}
TCP粘包和拆包
TCP是基于流的
当客户端发送多个包 服务端只收到一个包(多个包合成了一个包) 此时发生粘包
当客户端发送多个包 服务端也接收到多个包,但是包不完整(多了或少了数据 多了的数据是下一个包的 少了的数据会跟随下一个包一起发送过来的) 把一个完整的包拆成一个不完整 此时发生了拆包
UDP不会发生粘包和拆包 udp是基于报文的 在udp的首部会使用16bit存储报文的超度 因此不会发生粘拆包
TCP发生粘拆包的原因:要发送的数据先经过TCP的缓冲区
1.如果要发送的数据>TCP剩余的缓存区大小 发生拆包
2.如果要发送的数据>大于报文长度 发生拆包
3.如果要发送的数据<<TCP剩余缓冲区的大小 发生粘包
4.接收数据的应用没有及时读取缓冲去的数据 也会发送粘包
解决:
1.设置消息的长度
2.使用分隔符设置消息的边界
Netty提供的解决粘包拆包问题的解码器
A:基于长度的解码器 在包头部设置数据的长度
LengthFiledBasedFrameDecoder 自定义长度的处理方式
FixedLengthFreameDecoder 固定长度的处理方式
B:基于分隔符的解码器
DelimiterBasedFrameDecoder 自定义分隔符处理方式
LineBaseFrameDecoder 行尾(\n,\r\n)分隔符的处理方式 System.getProperty("line.separator") 系统分隔符
Netty引入Thymeleaf
在Thymeleaf中将数据渲染完成后会把整个页面 再一次形成字符串返回来
//获取模板引擎
@Autowired
private TemplateEngine templateEngine;
//对文件夹进行遍历 thymeleaf简化
public String fileListByEngine(String path, String uri) {
File file =new File(path);
List<String> nameList = new ArrayList<>();
for (File f : file.listFiles()) {
nameList.add(f.getName());
}
//使用thymeleaf渲染
//通过Context对象存储在Thymeleaf中使用的数据
Context context = new Context();
Map<String, Object> map = new HashMap<>();
map.put("path", path);
map.put("nameList", nameList);
//存入Context对象中
context.setVariables(map);
//对页面进行渲染 参数 页面名字 渲染内容
//将数据传给指定的页面 返回的字符串就是渲染好的完整页面 直接将字符串写入netty就可以了 省去了拼接字符串的过程
String content = templateEngine.process("fileList", context);
return content;//返回出去的就是完整的html字符串
}
**html**
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>http文件服务</title>
</head>
<body>
<h3>
<p th:text="${path}"></p>
</h3>
<ul >
<li th:each="name : ${nameList}"> 直接使用传来的key 回去值 最后将这个页面当做字符串返回去
链接:<a th:href="${name}" th:text="${name}"></a>
</li>
</ul>
</body>
</html>
