SpringBoot + WebSocket+STOMP指定推送消息

这篇具有很好参考价值的文章主要介绍了SpringBoot + WebSocket+STOMP指定推送消息。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。

一、前提条件

本文将简单的描述SpringBoot + WebSocket+STOMP指定推送消息场景,不包含信息安全加密等,请勿用在生产环境。

1.2 环境要求

JDK:11+
Maven: 3.5+
SpringBoot: 2.6+
stompjs@7.0.0

STOMP 是面向简单(或流式)文本的消息传递协议。 STOMP 提供可互操作的有线格式,以便 STOMP 客户端可以与任何 STOMP消息代理进行通信,从而在多种语言、平台和代理之间提供简单且广泛的消息互操作性。

1.3 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、相关工具类准备

2.1 发送消息载体

@Data
public class MessageOut{
   //这里的内容按需求来写,我随便举几个
    private String userId;
    private String name;
    private String message;
    private Integer status;
}

2.2 接收消息载体

@Data
public class MessageIn{
  //这里的内容按需求来写,我随便举几个
  private String content
}

2.3 消息处理接口

在 Spring 使用 STOMP 消息传递的方法中,STOMP 消息可以路由到@Controller类。基于这点我们写一个Controller类:

@RestController
public class MessageController {

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/message")
    @SendTo("/topic/messageTo")
    public MessageOut message(MessageIn message) {
         MessageOut m = new MessageOut(); 
         m.setMessage("有内鬼,终止交易");
         //在这里将推送地址改成 /topic/+要发送的id,即可实现点对点
         messagingTemplate.convertAndSend("/topic/12345","收到,ol");
        return m;
    }
}

2.4 为 STOMP 消息传递配置 Spring

配置类很简单,如下:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //启用一个简单的基于内存的消息代理,将问候消息传送回前缀为/topic的目的地上的客户端
        config.enableSimpleBroker("/topic");
        //指定绑定/app到用 @MessageMapping 注释的方法的消息的前缀,该前缀将用于定义所有消息映射
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册/pda-message-websocket连接的端点,并设置允许连接的原点
        registry.addEndpoint("/pda-message-websocket").setAllowedOrigins("*");

    }
}

到这里,后端部分编写完成~

三、前端部分

这部分就是一个验证而已,没啥技术含量,我们继续以往的前端风格,给一段代码自己体会:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
  <title>Hello WebSocket</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">浏览器不支持Javascript!Websocket依赖于启用的Javascript,请启用Javascript并重新加载此页面!</h2></noscript>
<div id="main-content" class="container">
  <div class="row">
    <div class="col-md-6">
      <form class="form-inline">
        <div class="form-group">
          <label for="connect">WebSocket 连接:</label>
          <button id="connect" class="btn btn-default" type="submit">连接</button>
          <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">断开
          </button>
        </div>
      </form>
    </div>
    <div class="col-md-6">
      <form class="form-inline">
        <div class="form-group">
          <label for="name">你叫什么?</label>
          <input type="text" id="name" class="form-control" placeholder="输入你的名字">
        </div>
        <button id="send" class="btn btn-default" type="submit">发送</button>
      </form>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <table id="conversation" class="table table-striped">
        <thead>
        <tr>
          <th>消息</th>
        </tr>
        </thead>
        <tbody id="greeting">
        </tbody>
      </table>
    </div>
  </div>
</div>
</body>
<script>
  const url = "ws://localhost:6060/pda-message-websocket";
  const stompClient = new StompJs.Client({
    brokerURL: url,
    connectHeaders: {
      // login: 'user',
      // passcode: 'password',
    },
    debug: function (str) {
      console.log(str);
    },
    //重连间隔 ms
    reconnectDelay: 5000,
    //发送心跳 ms
    heartbeatIncoming: 4000,
    //接收心跳 ms
    heartbeatOutgoing: 4000,
    logRawCommunication: false,
  });

  //默认使用WebSockets,如果浏览器不支持,则回退到SockJS
  if (typeof WebSocket !== 'function') {
    // 对于SockJS,需要设置一个工厂来创建一个新的SockJS实例
    // 用于每次(重新)连接
    stompClient.webSocketFactory = function () {
    // 请注意,URL与WebSocket URL不同
    return new SockJS('http://localhost:6060/notify');
    };
  }

  stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    //在这里将订阅改成 /topic/+自己的id,即可收到点对点发送的消息
    stompClient.subscribe('/topic/notify', (greeting) => {
      showGreeting(JSON.parse(greeting.body));
    });
  };

  stompClient.onWebSocketError = (error) => {
    console.error('Error with websocket', error);
  };

  stompClient.onStompError = (frame) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
  };

  function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
      $("#conversation").show();
    }
    else {
      $("#conversation").hide();
    }
    $("#greetings").html("");
  }

  function connect() {
    stompClient.activate();
  }

  function disconnect() {
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
  }

  function sendName() {
    stompClient.publish({
      destination: "/app/notify",
      body: JSON.stringify({'name': $("#name").val()})
    });
  }

  function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
  }

  $(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
  });
</script>
</html>

四、效果

点击前端代码HTML,可以看到一下效果:

stomp发送消息,springboot,spring boot,websocket,后端
点击连接,我们可以看到控制台上打印的连接信息和订阅信息,表明我们已经成功连接到服务器。

输入名称,点击发送可以看到:
stomp发送消息,springboot,spring boot,websocket,后端

我们再看看消息返回:
stomp发送消息,springboot,spring boot,websocket,后端
点对点返回:
stomp发送消息,springboot,spring boot,websocket,后端文章来源地址https://www.toymoban.com/news/detail-627332.html

到了这里,关于SpringBoot + WebSocket+STOMP指定推送消息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 (一)(1)

    server: port: 9908 3.WebSocketConfig.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.springfra

    2024年04月25日
    浏览(32)
  • Spring Boot 3 + Vue 3 整合 WebSocket (STOMP协议) 实现广播和点对点实时消息

    🚀 作者主页: 有来技术 🔥 开源项目: youlai-mall 🍃 vue3-element-admin 🍃 youlai-boot 🌺 仓库主页: Gitee 💫 Github 💫 GitCode 💖 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请纠正! WebSocket是一种在Web浏览器与Web服务器之间建立双向通信的协议,而Spring Boot提供了便捷的WebSocket支持

    2024年02月02日
    浏览(37)
  • uni-app + SpringBoot +stomp 支持websocket 打包app

    websocket 协议是在http 协议的基础上的升级,通过一次http 请求建立长连接,转而变为TCP 的全双工通信;而http 协议是一问一答的请求方式方式。 websocket-uni.js

    2024年02月11日
    浏览(30)
  • websocket + stomp + sockjs学习

    Spring WebSocket整合Stomp源码详解 PDF版本 Spring SpringBoot官方文档资料 spring5.1.9官方文档关于websocket的介绍 spring5.3.29官方文档关于websocket的介绍 WebSocket入门教程示例代码,代码地址已fork至本地gitee,原github代码地址,源老外的代码地址 [WebSocket入门]手把手搭建WebSocket多人在线聊天

    2024年02月12日
    浏览(24)
  • WebSocket—STOMP详解(官方原版)

    WebSocket协议定义了两种类型的消息(文本和二进制),但其内容未作定义。该协议定义了一种机制,供客户端和服务器协商在WebSocket之上使用的子协议(即更高级别的消息传递协议),以定义各自可以发送何种消息、格式是什么、每个消息的内容等等。子协议的使用是可选的

    2024年02月04日
    浏览(29)
  • flutter开发实战-长链接WebSocket使用stomp协议stomp_dart_client

    flutter开发实战-长链接WebSocket使用stomp协议stomp_dart_client 在app中经常会使用长连接进行消息通信,这里记录一下基于websocket使用stomp协议的使用。 1.1 stomp介绍 stomp,Streaming Text Orientated Message Protocol,是流文本定向消息协议,是一种为MOM(Message Oriented Middleware,面向消息的中间件

    2024年02月13日
    浏览(33)
  • 基于SockJS+Stomp的WebSocket实现

    前言     之前做个一个功能,通过websocket长链接接收后台推送的数据,然后在前端动态渲染。一直没来的及输出个文档,现在输出一下。 WebSocket介绍     WebSocket 是一种在 Web 应用中实现实时通信的方法,它可以在客户端和服务器端之间建立长连接,实现实时消息传递。  

    2024年02月12日
    浏览(27)
  • 整合 WebSocket 基于 STOMP 协议实现广播

    SpringBoot 实战 (十六) | 整合 WebSocket 基于 STOMP 协议实现广播 如题,今天介绍的是 SpringBoot 整合 WebSocket 实现广播消息。 什么是 WebSocket ? WebSocket 为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服务器发送信息,反之也成立。 WebSocket 是通过一个 socket 来实现双

    2024年01月21日
    浏览(37)
  • HTTP、WebSocket、STOMP、MQTT 协议

    TCP/IP 是用于因特网 (Internet) 的通信协议,是对计算机必须遵守的规则的描述,只有遵守这些规则,计算机之间才能进行通信。 TCP/IP是基于TCP和IP这两个最初的协议之上的不同的通信协议的大集合,是一个协议族。 1-1、TCP(传输控制协议,Transmission Control Protocol) 在计算机网

    2024年04月15日
    浏览(35)
  • WebSocket(三) -- 使用websocket+stomp实现群聊功能

    SpringBoot+websocket的实现其实不难,你可以使用原生的实现,也就是websocket本身的OnOpen、OnClosed等等这样的注解来实现,以及对WebSocketHandler的实现,类似于netty的那种使用方式,而且原生的还提供了对websocket的监听,服务端能更好的控制及统计(即上文实现的方式)。 但是,真

    2023年04月08日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包