Spring Boot使用WebSocket

spring boot集成websocket

WebSocket协议RFC 6455提供了一种标准化方法,可通过单个TCP连接在客户端和服务器之间建立全双工双向通信通道。 它是与HTTP不同的TCP协议,但旨在通过端口80和443在HTTP上工作,并允许重复使用现有的防火墙规则。

WebSocket是全双工双向通信通道, 因此服务器和客户端可以相互进行通信, 而不像HTTP那样只能一个Request对应一个Response,且Response只能被动相应。

集成步骤

  1. 引用Maven依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
  2. 实现WebSocketHandler接口,该接口中需要实现的方法便是在websocket连接中的各种状态(生命周期)的方法,这些方法中定义对WebSocket消息的一种处理

    /**
     * 实现消息处理类
     */
    @Component
    public class MessageHandler implements WebSocketHandler {
         
        
        // 存储WebSocketSession, 要保证线程安全, 因此使用ConcurrentHashMap
        private Map<String, WebSocketSession> map = new ConcurrentHashMap<>();
    
        /**
         * websocket连接后调用该方法
         * @param webSocketSession
         * @throws Exception
         */
        @Override
        public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
         
            System.out.println("--------------------------websocket连接------------------------------");
            System.out.println("连接id:" + webSocketSession.getId());
            map.put(webSocketSession.getId(), webSocketSession);
        }
    
        /**
         * 接受websocket消息
         * @param webSocketSession
         * @param webSocketMessage
         * @throws Exception
         */
        @Override
        public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
         
            System.out.println("-------------------------------webs
Spring Boot 中集成 WebSocket 可以为应用程序添加实时双向通信的功能,非常适合构建聊天室、股票行情更新等功能。下面是详细步骤及配置说明: ### 一、引入依赖 首先,在 `pom.xml` 文件中加入 Spring WebSocket 的 Starter 包以及 STOMP (Simple Text Oriented Messaging Protocol) 支持(STOMP 是一种简单的文本消息传递协议,常用于浏览器客户端和服务器间的交互)。 ```xml <dependencies> <!-- 其他已有依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- 若需支持STOMP协议,则还需加上下面这条依賴 --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> </dependencies> ``` ### 二、配置 WebSocket 消息代理 创建一个新的配置类来设置 WebSocket 和 STOMP 端点映射规则,并指定是否启用基于内存的消息代理或外部消息中间件如 RabbitMQ 或 ActiveMQ。 ```java import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker // 启动WebSocket消息代理功能 public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); // 设置订阅前缀(即目的地) config.setApplicationDestinationPrefixes("/app"); // 应用程序请求的目的地前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").withSockJS(); // 注册一个供前端连接的端点,并开启 SockJS 协议兼容模式 } } ``` ### 三、编写处理器 Controller 接下来定义一个控制器类接收来自客户端发送过来的消息并广播出去。这里我们将演示如何监听 `/chat.sendMessage` 目的地并将收到的信息转发到所有已订阅该主题 (`/topic/messages`) 的客户端上。 ```java import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class ChatController { /** * 当接收到指向 /app/chat.sendMessage 地址的消息时触发此方法. */ @MessageMapping("/chat.sendMessage") @SendTo("/topic/messages") // 将结果返回给订阅了 /topic/messages 主题的所有客户机 public String processChat(String messageContent){ return "Received from client: "+messageContent; } } ``` ### 四、前台页面实现部分 最后一步就是在 HTML 页面里利用 JavaScript 客户端库建立与服务器之间的 Web Socket 连接并向其发送数据包。这里给出一段简易示例代码片段展示如何使用 sockjs-client 和 stomp.js 来完成上述操作。 ```html <!-- index.html --> <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/stompjs/lib/stomp.min.js"></script> <script type="text/javascript"> var socket = new SockJS('/ws'); // 创建新的Socks实例并与服务端握手建连 var stompClient = Stomp.over(socket); stompClient.connect({}, function(frame){ // 成功链接后注册回调函数等待接收通知信息 console.log('Connected: ' + frame); stompClient.subscribe('/topic/messages', function(messageOutput){ alert("New Message Arrived:" + JSON.parse(messageOutput.body).content) }); }); // 发送一条新消息至服务器端 function sendMessage() { var content = document.getElementById('msg').value; stompClient.send("/app/chat.sendMessage", {}, JSON.stringify({'content':content})); } </script> <input id="msg" placeholder="Enter your msg"/> <button onclick="sendMessage()">Send Msg</button> ``` 综上所述,我们已经在 Spring Boot 上成功集成了 WebSocket 功能并通过 STOMP 规范实现了基本的发布 - 订阅模型。实际项目中可根据需求进一步扩展和完善相应逻辑模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值