<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.20.Final</version>
</dependency>
package com.example.demo.controller.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
//服务端
public class MyServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup boss=new NioEventLoopGroup();
EventLoopGroup worker=new NioEventLoopGroup();
try {
ServerBootstrap bootstrap=new ServerBootstrap();
bootstrap.group(boss,worker)
.channel(NioServerSocketChannel.class)
//对boss进行记录处理程序
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//因为基于http协议 使用http的编码和解码器
pipeline.addLast(new HttpServerCodec());
//是以块方式写 添加处理器
pipeline.addLast(new ChunkedWriteHandler());
//http数据在传输过程中是分段 就是可以将多个段聚合 这就是为什么当浏览器发生大量数据时 就会发生多次http请求
pipeline.addLast(new HttpObjectAggregator(8192));
//对应websocket 他的数据是以帧(frame) 形式传递 可以看到websocketframe 下面有6个子类
//浏览器请求时 ws://localhost:7777/hello 表示请求的uri
//核心功能是将http协议升级为ws协议,保持长连接
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义处理程序
pipeline.addLast(new MyServerHandler());
}
});
//绑定端口
ChannelFuture sync = bootstrap.bind(7777).sync();
//监听关闭
sync.channel().closeFuture().sync();
}finally {
//优雅关闭
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
package com.example.demo.controller.http;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import java.time.LocalDateTime;
//服务端业务处理程序 TextWebSocketFrame表示文本帧
public class MyServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
//服务器读取通道的数据
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
System.out.println("服务器收到消息:"+textWebSocketFrame.text());
//给客户端写消息
channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器时间"+ LocalDateTime.now()+" "+textWebSocketFrame.text()));
}
//当web客户端连接上 触发该方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded被调用了:"+ctx.channel().id().asLongText());
System.out.println("handlerAdded被调用了:"+ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved被调用了:"+ctx.channel().id().asLongText());
}
//异常 关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("发送异常"+cause.getMessage());
ctx.close();
}
}
新建一个hello.html界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var socket;
//判断当前浏览器是否支持websocket
if(window.WebSocket){
socket=new WebSocket("ws://localhost:7777/hello");
//相当于channelRead0 收到服务器端 发送的消息
socket.onmessage=function (ev) {
//显示到长文本中
var rt = document.getElementById('resText');
rt.value=rt.value+"\n" +ev.data;
}
//连接开启
socket.onopen=function (ev) {
var rt=document.getElementById("resText");
rt.value="连接开启了";
}
//连接关闭
socket.onclose=function (ev) {
var rt=document.getElementById("resText");
rt.value=rt.value+"\n"+"连接关闭了";
}
}else {
alert("当前浏览器不支持websocket");
}
//发送消息给服务器
function send(message) {
//判断socket是否创建好
if(!window.socket){
return;
}
if(socket.readyState==WebSocket.OPEN){
//通过socket发送消息
socket.send(message);
}else {
alert("连接没有开启");
}
}
</script>
<body>
<form onsubmit="return false">
<textarea name="message" style="height: 300px;width: 300px"></textarea>
<input type="button" value="发送消息" onclick="send(this.form.message.value)">
<textarea id="resText" style="height: 300px;width: 300px"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('resText').value=''">
</form>
</body>
</html>
启动服务端,打开html界面
netty就是通过101这个状态码升级成的websocket