netty实现websocket推送消息
前⾔
由于http协议为应答模式的连接,⽆法保持长连接于是引⼊了websocket套接字长连接概念,能够保持数据持久性的交互;本篇⽂章将告知读者如何使⽤netty实现简单的消息推送功能websocket请求头GET / HTTP/1.1
Host: 127.0.0.1:8096Connection: UpgradePragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36Upgrade: websocket
Origin: http://localhost:8056Sec-WebSocket-Version: 13
websocket请求头 会有 Connection 升级为 Upgrade, 并且Upgrade 属性值为 websocket引⼊依赖
引⼊netty和 引擎模板依赖 io.netty netty-all 4.1.55.Final
org.springframework.boot
spring-boot-starter-thymeleaf
创建WebSocketServer
创建Nio线程组,并在辅助启动器中中注⼊ ⾃定义处理器;定义套接字端⼝为8096;/**
* @author lsc *
*/
@Slf4j
public class WebSocketServer {
public void init(){
NioEventLoopGroup boss=new NioEventLoopGroup(); NioEventLoopGroup work=new NioEventLoopGroup(); try {
ServerBootstrap bootstrap=new ServerBootstrap(); bootstrap.group(boss,work);
bootstrap.channel(NioServerSocketChannel.class); // ⾃定义处理器
bootstrap.childHandler(new SocketChannelInitializer()); Channel channel = bootstrap.bind(8096).sync().channel();
log.info(\"------------webSocket服务器启动成功-----------:\"+channel); channel.closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace();
log.info(\"---------运⾏出错----------:\"+e); }finally {
boss.shutdownGracefully(); work.shutdownGracefully();
log.info(\"------------websocket服务器已关闭----------------\"); } }}
SocketChannelInitializer
SocketChannelInitializer 中定义了聚合器 HttpObjectAggregator 将多个http⽚段消息聚合成完整的http消息,并且指定⼤⼩为65536;最后注⼊⾃定义的WebSocketHandler;/**
* @author lsc *
*/
public class SocketChannelInitializer extends ChannelInitializer { @Overrideprotected void initChannel(SocketChannel ch) { //设置log监听器
ch.pipeline().addLast(\"logging\ //设置解码器
ch.pipeline().addLast(\"http-codec\ //聚合器
ch.pipeline().addLast(\"aggregator\ //⽤于⼤数据的分区传输
ch.pipeline().addLast(\"http-chunked\ //⾃定义业务handler
ch.pipeline().addLast(\"handler\ }}
WebSocketHandler
WebSocketHandler 中对接收的消息进⾏判定,如果是websocket 消息 则将消息⼴播给所有通道;/**
* @author lsc *
*/@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler