Spring Boot + WebSocket(广播的方式发送消息)

    科技2024-12-06  15

    使用广播的方式,该方式将消息发送给所有连接了当前endpoint的浏览器

    1.添加websocket依赖
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
    2.配置WebSocket,需要在配置类上使用@EnableWebSocketMessageBroker注解开启WebSocket支持,并通过实现WebSocketMessageBrokerConfigurer接口的registerStompEndpoints和configureMessageBroker完成WebSocket配置
    @Configuration @EnableWebSocketMessageBroker//开启使用STOMP协议来传输基于代理(message broker)的消息 public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { //注册STOMP协议的节点(endPoint),并映射指定的URL @Override public void registerStompEndpoints(StompEndpointRegistry registry){ registry.addEndpoint("/endpoint").withSockJS();//注册一个STOMP的endpoint,并指定SockJS协议 } //配置消息代理(Message Broker) @Override public void configureMessageBroker(MessageBrokerRegistry registry){ registry.enableSimpleBroker("/topic"); } }
    3.浏览器向服务端发送消息的实体类
    public class SendMessageBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
    4.服务端向浏览器发送信息的实体类
    public class ReceiveMessageBean { private String responseMessage; public ReceiveMessageBean(String responseMessage) { this.responseMessage = responseMessage; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } }
    5.控制器
    @Controller public class WsController { @MessageMapping("/welcome") //浏览器向服务端发送请求时,通过这个映射,相当于@RequestMapping @SendTo("/topic/getResponse") //当服务端有消息时,会对订阅了@SendTo中的路径的浏览器发送消息 public ReceiveMessageBean say(SendMessageBean message) throws Exception{ return new ReceiveMessageBean("hello," + message.getName() + "!"); } }
    6.演示页面(该页面用到了thymeleaf模版,所以需要引入该模版依赖)
    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
    页面
    <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>WebSocket广播式</title> </head> <body onload="disconnect()"> <noscript><h2 style="color: #ff0000">您的浏览器不支持websocket</h2></noscript> <div> <div> <button id="connect" onclick="connect();">连接</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button> </div> <div id="conversationDiv"> <label>需要发送的消息</label><input type="text" id="name" /> <button id="sendName" onclick="sendName();">发送</button> <p id="response"></p> </div> </div> <script th:src="@{sockjs.min.js}"></script> <script th:src="@{stomp.min.js}"></script> <script th:src="@{jquery.js}"></script> <script type="text/javascript"> var stompClient = null; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden'; $('#response').html(); } function connect() { var socket = new SockJS('/endpoint'); //连接SockJS的endpoint名称为"/endpoint" stompClient = Stomp.over(socket);//使用STOMP子协议的WebSocket客户端 stompClient.connect({}, function(frame) {//连接WebScoket服务端 setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/getResponse', function(respnose){ //订阅消息 showResponse(JSON.parse(respnose.body).responseMessage); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } function sendName() { var name = $('#name').val(); stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));//发送消息 } function showResponse(message) { var response = $("#response"); response.html(message); } </script> </body> </html>
    7.该页面需要的js

    链接: https://pan.baidu.com/s/1LC1JNdm-R9yU49GIGm4M1w 密码: l808

    Processed: 0.015, SQL: 8