Springboot Netty Websocket如何实现长尾词消息推送?

2026-04-19 19:212阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计973个文字,预计阅读时间需要4分钟。

Springboot Netty Websocket如何实现长尾词消息推送?

前言:WebSocket+使用,使得客户端和服务器之间的数据交换变得更加简单,允许服务器主动向客户端推送数据。在WebSocket API中,浏览器和服务端仅需完成一次握手,两者之间即可直接建立连接。

前言

WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

Springboot Netty Websocket如何实现长尾词消息推送?

Netty框架的优势

1. API使用简单,开发门槛低;
2. 功能强大,预置了多种编解码功能,支持多种主流协议;
3. 定制能力强,可以通过ChannelHandler对通信框架进行灵活地扩展;
4. 性能高,通过与其他业界主流的NIO框架对比,Netty的综合性能最优;
5. 成熟、稳定,Netty修复了已经发现的所有JDK NIO BUG,业务开发人员不需要再为NIO的BUG而烦恼

提示:以下是本篇文章正文内容,下面案例可供参考

一、引入netty依赖

<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.48.Final</version> </dependency>

二、使用步骤

1.引入基础配置类

package com.test.netty; public enum Cmd { START("000", "连接成功"), WMESSAGE("001", "消息提醒"), ; private String cmd; private String desc; Cmd(String cmd, String desc) { this.cmd = cmd; this.desc = desc; } public String getCmd() { return cmd; } public String getDesc() { return desc; } }

2.netty服务启动监听器

package com.test.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; /** * @author test * <p> * 服务启动监听器 **/ @Slf4j @Component public class NettyServer { @Value("${server.netty.port}") private int port; @Autowired private ServerChannelInitializer serverChannelInitializer; @Bean ApplicationRunner nettyRunner() { return args -> { //new 一个主线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //new 一个工作线程组 EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(serverChannelInitializer) //设置队列大小 .option(ChannelOption.SO_BACKLOG, 1024) // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 .childOption(ChannelOption.SO_KEEPALIVE, true); //绑定端口,开始接收进来的连接 try { ChannelFuture future = bootstrap.bind(port).sync(); log.info("服务器启动开始监听端口: {}", port); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { //关闭主线程组 bossGroup.shutdownGracefully(); //关闭工作线程组 workGroup.shutdownGracefully(); } }; } }

3.netty服务端处理器

package com.test.netty; import com.test.common.util.JsonUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.localhost:port/test.io"); ws.onopen = function() { // Web Socket 已连接上,使用 send() 方法发送数据 ws.send("发送数据"); alert("数据发送中..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("数据已接收..."); }; ws.onclose = function() { // 关闭 websocket alert("连接已关闭..."); }; } else { // 浏览器不支持 WebSocket alert("您的浏览器不支持 WebSocket!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()" rel="external nofollow" >运行 WebSocket</a> </div> </body> </html>

7.vue测试

mounted() { this.initWebsocket(); }, methods: { initWebsocket() { let websocket = new WebSocket('ws://localhost:port/test.io?test=123456'); websocket.onmessage = (event) => { let msg = JSON.parse(event.data); switch (msg.cmd) { case "000": this.$message({ type: 'success', message: "建立实时连接成功!", duration: 1000 }) setInterval(()=>{websocket.send("heartbeat")},60*1000); break; case "001": this.$message.warning("收到一条新的信息,请及时查看!") break; } } websocket.onclose = () => { setTimeout(()=>{ this.initWebsocket(); },30*1000); } websocket.onerror = () => { setTimeout(()=>{ this.initWebsocket(); },30*1000); } }, }, ![在这里插入图片描述](img.558idc.com/uploadfile/allimg/java/20210107160420568.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d1X3Fpbmdfc29uZw==,size_16,color_FFFFFF,t_70#pic_center)

8.服务器下发消息

@Autowired private NettyServerHandler nettyServerHandler; nettyServerHandler.send(CmdWeb.WMESSAGE, id, message);

到此这篇关于Springboot+Netty+Websocket实现消息推送实例的文章就介绍到这了,更多相关Springboot Websocket消息推送内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

本文共计973个文字,预计阅读时间需要4分钟。

Springboot Netty Websocket如何实现长尾词消息推送?

前言:WebSocket+使用,使得客户端和服务器之间的数据交换变得更加简单,允许服务器主动向客户端推送数据。在WebSocket API中,浏览器和服务端仅需完成一次握手,两者之间即可直接建立连接。

前言

WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

Springboot Netty Websocket如何实现长尾词消息推送?

Netty框架的优势

1. API使用简单,开发门槛低;
2. 功能强大,预置了多种编解码功能,支持多种主流协议;
3. 定制能力强,可以通过ChannelHandler对通信框架进行灵活地扩展;
4. 性能高,通过与其他业界主流的NIO框架对比,Netty的综合性能最优;
5. 成熟、稳定,Netty修复了已经发现的所有JDK NIO BUG,业务开发人员不需要再为NIO的BUG而烦恼

提示:以下是本篇文章正文内容,下面案例可供参考

一、引入netty依赖

<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.48.Final</version> </dependency>

二、使用步骤

1.引入基础配置类

package com.test.netty; public enum Cmd { START("000", "连接成功"), WMESSAGE("001", "消息提醒"), ; private String cmd; private String desc; Cmd(String cmd, String desc) { this.cmd = cmd; this.desc = desc; } public String getCmd() { return cmd; } public String getDesc() { return desc; } }

2.netty服务启动监听器

package com.test.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; /** * @author test * <p> * 服务启动监听器 **/ @Slf4j @Component public class NettyServer { @Value("${server.netty.port}") private int port; @Autowired private ServerChannelInitializer serverChannelInitializer; @Bean ApplicationRunner nettyRunner() { return args -> { //new 一个主线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(1); //new 一个工作线程组 EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .childHandler(serverChannelInitializer) //设置队列大小 .option(ChannelOption.SO_BACKLOG, 1024) // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文 .childOption(ChannelOption.SO_KEEPALIVE, true); //绑定端口,开始接收进来的连接 try { ChannelFuture future = bootstrap.bind(port).sync(); log.info("服务器启动开始监听端口: {}", port); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { //关闭主线程组 bossGroup.shutdownGracefully(); //关闭工作线程组 workGroup.shutdownGracefully(); } }; } }

3.netty服务端处理器

package com.test.netty; import com.test.common.util.JsonUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.localhost:port/test.io"); ws.onopen = function() { // Web Socket 已连接上,使用 send() 方法发送数据 ws.send("发送数据"); alert("数据发送中..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("数据已接收..."); }; ws.onclose = function() { // 关闭 websocket alert("连接已关闭..."); }; } else { // 浏览器不支持 WebSocket alert("您的浏览器不支持 WebSocket!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()" rel="external nofollow" >运行 WebSocket</a> </div> </body> </html>

7.vue测试

mounted() { this.initWebsocket(); }, methods: { initWebsocket() { let websocket = new WebSocket('ws://localhost:port/test.io?test=123456'); websocket.onmessage = (event) => { let msg = JSON.parse(event.data); switch (msg.cmd) { case "000": this.$message({ type: 'success', message: "建立实时连接成功!", duration: 1000 }) setInterval(()=>{websocket.send("heartbeat")},60*1000); break; case "001": this.$message.warning("收到一条新的信息,请及时查看!") break; } } websocket.onclose = () => { setTimeout(()=>{ this.initWebsocket(); },30*1000); } websocket.onerror = () => { setTimeout(()=>{ this.initWebsocket(); },30*1000); } }, }, ![在这里插入图片描述](img.558idc.com/uploadfile/allimg/java/20210107160420568.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d1X3Fpbmdfc29uZw==,size_16,color_FFFFFF,t_70#pic_center)

8.服务器下发消息

@Autowired private NettyServerHandler nettyServerHandler; nettyServerHandler.send(CmdWeb.WMESSAGE, id, message);

到此这篇关于Springboot+Netty+Websocket实现消息推送实例的文章就介绍到这了,更多相关Springboot Websocket消息推送内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!