SpringBoot的Web开发之WebSocket(广播式)笔记总结

战斗前准备:新建Spring Boot项目选择Thymeleaf和WebSocket依赖

1.配置WebSocket

配置WebSocket.需要在配置类上使用@EnableWebSocketMessageBroker开启WebSocket支持,并实现WebSocketMessageBrokerConfigurer接口,重写方法来配置WebSocket

(SpringBoot颠覆者里是继承AbstractWebSocketMessageBrokerConfigurer 类,但是那个类已经过时了)

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;
/**
 * 第一步,配置WebSocket.需要在配置类上使用@EnableWebSocketMessageBroker开启WebSocket支持
 * 并实现WebSocketMessageBrokerConfigurer接口
 * 重写方法来配置WebSocket
 */
@Configuration
//通过@EnableWebSocketMessageBroker注解开启使用STOMP协议在传输基于代理(message broker)的消息
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    
    //注册STOMP协议的节点(endpoint),并映射指定的URL
    public void registerStompEndpoints(StompEndpointRegistry registry){
    
    
        //注册一个STOMP的endpoint,并指定使用SockJS协议
        registry.addEndpoint("/endpointWisely").withSockJS();
    }
    //配置消息代理(Message Broker)
    public void configureMessageBroker(MessageBrokerRegistry registry){
    
    
        //广播式配置一个/topic消息代理
        registry.enableSimpleBroker("/topic");
    }
}

2.编写浏览器向服务端发送消息(服务端用该类接收)

//浏览器向服务端发送的消息用此类接收
public class WiselyMessage {
    
    
    public String name;
    public String getName(){
    
    
        return  name;
    }
}

3. 编写服务端向浏览器发送消息(服务端用该类发送)

//服务端向浏览器发送的此类的消息
public class WiselyResponse {
    
    
    private String responseMessage;
    public WiselyResponse(String responseMessage){
    
    
        this.responseMessage = responseMessage;
    }

    public String getResponseMessage() {
    
    
        return responseMessage;
    }
}

4. 编写一个Controller用于模拟发送和接收

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import test.demo4.domain.WiselyMessage;
import test.demo4.domain.WiselyResponse;

@Controller
public class WsController {
    
    
    //当浏览器向服务端发送请求时,通过@MessageMapping映射/welcome这个地址,类似于@RequestMapping
    @MessageMapping("/welcome")
    //当服务端有消息时,会订阅了@SendTo中的路径的浏览器发送消息
    @SendTo("/topic/getResponse")
    public WiselyResponse say(WiselyMessage message)throws Exception{
    
    
        Thread.sleep(3000);
        return new WiselyResponse("Welcome   "+message.getName()+"  !");
    }
}

5.添加脚本

将stomp.min.js、scokjs.min.js和jquery.js放置在src/main/resources/static下
找资源太难的话,当然已经为你们准备好啦!
链接失效的话后台私信我哦!
链接:https://pan.baidu.com/s/1UsP-4w1OkTUiz_YvVgFlVQ
提取码:9wpf
在这里插入图片描述

6. 编写一个页面来演示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Spring Boot+WebSoc+广播式</title>
</head>
<body onload="disconnect()">
  <noscript><h2 style="color: #ff0000">貌似浏览器不支持WebSocket</h2></noscript>
<div>
  <div>
    <button id="connect" onclick="connect();">连接</button>
    <button id="disconnect" 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>
  <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() {
    
    
      //连接SockJS的endpoint名称为"/endpointWisely"
      var socket = new SockJS('/endpointWisely');
      //使用STOMP子协议的WebSocket客户端
      stompClient = Stomp.over(socket);
      //连接WebSocket服务端
      stompClient.connect({
    
    },function (frame) {
    
    
        setConnected(true);
        console.log('Connected:'+frame);
        //通过stompClient.subscribe订阅/topic/getResponse目标(destination)发送消息
        //这个是在控制器的@SendTo中定义的
        stompClient.subscribe('/topic/getResponse',function (response) {
    
    
          showResponse(JSON.parse(response.body).responseMessage);
        });
      });
    }

    function disconnect() {
    
    
      if (stompClient != null){
    
    
        stompClient.disconnect();
      }
      setConnected(false);
      console.log("Disconnected");
    }
    function sendName() {
    
    
      var name = $("#name").val();
      //通过stompClient.send向/welcome目标(destination)发送消息
      //这个是在控制器的@MessageMapping中定义的
      stompClient.send("/welcome",{
    
    },JSON.stringify({
    
    "name":name}));
    }
    function showResponse(message) {
    
    
      var response = $("#response");
      response.html(message);
    }
  </script>
</div>
</body>
</html>

7. 配置ViewController

为ws.html提供便捷的路径映射
将所有/static/** 访问都映射到classpath:/static/ 目录下

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    
	//为ws.html提供便捷的路径映射
    public void addViewControllers(ViewControllerRegistry registry){
    
    
        registry.addViewController("/ws").setViewName("/ws");
    }
  	//将所有/static/** 访问都映射到classpath:/static/ 目录下
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        System.out.println("==========静态资源拦截!============");
        registry.addResourceHandler("/static/**/").addResourceLocations("classpath:/static/");
    }
}

跑跑跑起来…
运行结果
ps:以上内容参考SpringBoot颠覆者,学习笔记,仅供参考

猜你喜欢

转载自blog.csdn.net/weixin_44864260/article/details/109252996
今日推荐