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

Stella981
• 阅读 569

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

广播式主要有7大步骤

  • 1.配置WebSocket
  • 2.编写浏览器向服务端发送消息(服务端用该类接收)
  • 3. 编写服务端向浏览器发送消息(服务端用该类发送)
  • 4. 编写一个Controller用于模拟发送和接收
  • 5.添加脚本
  • 6. 编写一个页面来演示
  • 7. 配置ViewController

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
SpringBoot的Web开发之WebSocket(广播式)笔记总结

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/");
    }
}

跑跑跑起来…
SpringBoot的Web开发之WebSocket(广播式)笔记总结
ps:以上内容参考SpringBoot颠覆者,学习笔记,仅供参考

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
SpringBoot的Web开发之WebSocket(广播式)笔记总结
战斗前准备:新建SpringBoot项目选择Thymeleaf和WebSocket依赖广播式主要有7大步骤1.配置WebSocket2.编写浏览器向服务端发送消息(服务端用该类接收)3\.编写服务端向浏览器发送消息(服务端用该类发送)4\.编写一个Controller用于模拟发送和接收
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这