SpringCloud(若依微服务版为例)集成WebSocket实现前后端的消息推送

263 篇文章 11 订阅 ¥9.90 ¥99.00
52 篇文章 3 订阅

场景

SpringBoot+Vue整合WebSocket实现前后端消息推送:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/114392573

若依微服务版手把手教你本地搭建环境并运行前后端项目:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/109363303

在上面介绍了在SpringBoot+Vue的基础上使用WebSocket的过程以及使用SpringCloud(若依微服务版)搭建项目的基础上,如果在SpringCloud中使用WebSocket的过程。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先在需用集成WebSocket的服务下面添加WebSocket的依赖

        <!-- WebSocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</ar
  • 5
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
要使用Undertow实现WebSocket前后端消息推送,可以按照以下步骤进行: 1. 在后端实现WebSocket处理器,代码如下: ```java import io.undertow.server.HttpServerExchange; import io.undertow.websockets.core.*; import io.undertow.websockets.spi.WebSocketHttpExchange; import io.undertow.websockets.spi.WebSocketSession; public class WebSocketHandler implements WebSocketConnectionCallback { @Override public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) { // WebSocket连接建立时触发 System.out.println("WebSocket连接建立"); // 创建WebSocket会话 WebSocketSession session = new UndertowWebSocketSession(channel); // 将WebSocket会话保存到会话管理器中 WebSocketSessionManager.addSession(session); // 注册WebSocket消息处理器 channel.getReceiveSetter().set(new WebSocketMessageHandler(session)); channel.resumeReceives(); } } class WebSocketMessageHandler implements WebSocketCallback<WebSocketChannel> { private WebSocketSession session; public WebSocketMessageHandler(WebSocketSession session) { this.session = session; } @Override public void onError(WebSocketChannel channel, Throwable throwable) { // WebSocket出错时触发 System.out.println("WebSocket出错"); throwable.printStackTrace(); } @Override public void onClose(WebSocketChannel channel, StreamSourceFrameChannel channel1) throws IOException { // WebSocket连接关闭时触发 System.out.println("WebSocket连接关闭"); // 从会话管理器中删除WebSocket会话 WebSocketSessionManager.removeSession(session); } @Override public void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) { // 收到完整的文本消息时触发 System.out.println("收到文本消息:" + message.getData()); // 处理WebSocket消息 // ... } } ``` 2. 在Undertow服务器中添加WebSocket处理器,代码如下: ```java import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.RoutingHandler; import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.server.handlers.resource.ResourceHandler; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.server.handlers.websocket.WebSocketProtocolHandshakeHandler; public class WebSocketServer { public static void main(String[] args) { // 创建Web资源管理器 ResourceManager resourceManager = new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), "web"); // 创建Web资源处理器 ResourceHandler resourceHandler = new ResourceHandler(resourceManager); // 创建WebSocket处理器 WebSocketConnectionCallback callback = new WebSocketHandler(); WebSocketProtocolHandshakeHandler websocketHandler = new WebSocketProtocolHandshakeHandler(callback); // 创建路由处理器 RoutingHandler routingHandler = Handlers.routing() .get("/", resourceHandler) .get("/{path}", resourceHandler) .get("/websocket", websocketHandler); // 创建路径处理器 PathHandler pathHandler = Handlers.path(routingHandler) .addPrefixPath("/", resourceHandler); // 创建Undertow服务器 Undertow server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(pathHandler) .build(); // 启动Undertow服务器 server.start(); } } ``` 3. 在前端使用WebSocket连接到后端,代码如下: ```javascript var websocket = new WebSocket("ws://localhost:8080/websocket"); websocket.onopen = function() { console.log("WebSocket连接建立"); }; websocket.onclose = function() { console.log("WebSocket连接关闭"); }; websocket.onerror = function() { console.log("WebSocket出错"); }; websocket.onmessage = function(event) { console.log("收到文本消息:" + event.data); }; ``` 4. 在后端向前端发送消息,代码如下: ```java import io.undertow.websockets.core.*; import io.undertow.websockets.spi.WebSocketSession; public class WebSocketSessionManager { private static Set<WebSocketSession> sessions = new HashSet<>(); public static void addSession(WebSocketSession session) { sessions.add(session); } public static void removeSession(WebSocketSession session) { sessions.remove(session); } public static void sendMessage(String message) { for (WebSocketSession session : sessions) { try { session.send(new StringWebSocketMessage(message)); } catch (IOException e) { e.printStackTrace(); } } } } ``` 调用`WebSocketSessionManager.sendMessage()`方法即可向所有前端客户端发送消息
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值