websocket使用案例(前后端springboot+vue)

这篇具有很好参考价值的文章主要介绍了websocket使用案例(前后端springboot+vue)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


前言

参考资料:spring官网
案例代码地址:https://spring.io/guides/gs/messaging-stomp-websocket/
官方文档地址:https://docs.spring.io/spring-framework/reference/web/websocket/stomp/message-flow.html

使用websocket进行简单的通信,功能大致为广播推送全体消息,根据不同用户推送特定消息

我这次使用后端springboot+前端vue实现websocket功能


一、什么时候使用websocket

websocket使用案例(前后端springboot+vue),websocket,spring boot,vue.js
官方文档说的很清楚了,协作、游戏、金融方面都会用到实时数据,其他对要求不高的可以用轮询代替。
我这次遇到的需要就是多用户协作。

二、大致需求

用户A新建一个模板,并分享给其他用户B、C使用,当用户B、C查询自己有哪些可用模板时,用户A对模板作了修改,此时用户B、C应该能感知到,不然使用时就会出问题。

三、简单代码实现

3.1 后端代码实现

后端maven依赖:

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

websocket服务器地址,核心模块:

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;

/**
 * @Author: Ron
 * @Create: 2023-09-27 17:44
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic","/user");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/webSocket")
                .setAllowedOrigins("*");
    }

}

消息处理模块

import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.SysTicket;
import org.jeecg.modules.system.mapper.SysTicketMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Ron
 * @Create: 2023-09-27 17:48
 */
@CrossOrigin
@RestController
public class WebsocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/hello")
    public void greeting() {
        messagingTemplate.convertAndSendToUser("ron.yu", "/queue/private", "convertAndSendToUser:Hello World!");
        messagingTemplate.convertAndSend("/topic/greetings", "convertAndSend:Hello, Ron!");
    }

}

配置文件

server:
  port: 8888
  servlet:
    context-path: /cq

3.2 前端代码

vue

<template>
  <div>
    <h1>WebSocket Example</h1>
    <button @click="connectWebSocket">Connect</button>
    <button @click="disconnectWebSocket">Disconnect</button>
    <input v-model="message" placeholder="Enter a message" />
    <button @click="sendMessage">Send Message</button>
    <ul>
      <li v-for="(greeting, index) in greetings" :key="index">{{ greeting }}</li>
    </ul>
  </div>
</template>

<script>
import SockJS from "sockjs-client";
import Stomp from "stompjs";

export default {
  data() {
    return {
      stompClient: null,
      message: "",
      greetings: [],
      username:""
    };
  },
  methods: {
    connectWebSocket() {
      const socket = new WebSocket("ws://localhost:8888/cq/webSocket"); // 替换成您的WebSocket服务器地址
      this.stompClient = Stomp.over(socket);

      this.stompClient.connect({}, frame => {
        console.log("WebSocket连接成功", frame);
        this.stompClient.subscribe("/topic/greetings", greeting => {
          // this.greetings.push(greeting.body);
          console.log("/topic/greetings");
        });
        this.stompClient.subscribe(`/user/${this.message}/queue/private`, message => {
          // 处理私人消息
          // console.log("Received private message:", JSON.parse(message.body));
          console.log("Received private message:");
        });
      });
    },
    disconnectWebSocket() {
      if (this.stompClient) {
        this.stompClient.disconnect(() => {
          console.log("WebSocket断开连接");
        });
      }
    },
    sendMessage() {
      if (this.message) {
        this.stompClient.send(
          "/app/hello",
          {},
          JSON.stringify({ name: this.message })
        );
        // this.message = "";
      }
    }
  }
};
</script>

3.3 页面效果展示

websocket使用案例(前后端springboot+vue),websocket,spring boot,vue.js

四、代码理解

websocket后端核心模块:
websocket使用案例(前后端springboot+vue),websocket,spring boot,vue.js
①:@EnableWebSocketMessageBroker,是一个标志,它告诉 Spring 该类用于配置和启用 WebSocket 服务,然后你需要在该类中定义实际的 WebSocket 端点和处理逻辑。这个注解使得构建 WebSocket 服务更加方便。通过合理配置消息代理,你可以实现消息的分发、广播和点对点通信等功能。
②:configureMessageBroker,用于配置消息代理,它是 WebSocketMessageBrokerConfigurer 接口中的一个方法。消息代理是 WebSocket 服务中的核心组件之一,它负责将消息从发送方传递到接收方,充当了消息的中转站。
③:config.enableSimpleBroker(“/topic”,“/user”),启用消息代理,意味着可以使用 “/topic” 和 “/user” 作为消息的目的地,消息将由代理传送到订阅这些目的地的客户端。
④:config.setApplicationDestinationPrefixes(“/app”),设置应用程序目的地前缀,设置了应用程序目的地的前缀为 “/app”。这意味着客户端可以将消息发送到以 “/app” 开头的目的地,然后消息代理将这些消息路由到相应的消息处理器进行处理。
⑤:registerStompEndpoints,用来定义和配置 WebSocket 端点的重要方法,它允许你指定端点的名称、允许的跨域源,以及其他相关配置。
⑥:registry.addEndpoint(“/webSocket”),注册了一个名为 “/webSocket” 的 WebSocket 端点。这意味着客户端可以通过 WebSocket 连接到 “/webSocket” 这个端点来进行实时通信。
⑦:.setAllowedOrigins("")*,跨域设置,设置了允许来自任何源的跨域 WebSocket 连接。

websocket使用案例(前后端springboot+vue),websocket,spring boot,vue.js
⑧:@MessageMapping(“/hello”),是 Spring Framework 中用于处理 WebSocket 消息映射的注解。它的作用是将客户端发送的消息映射到指定的处理方法,以便在接收到特定消息时执行相应的逻辑。
⑨:private SimpMessagingTemplate messagingTemplate;,是 Spring Framework 中的一个类,它用于发送消息到 WebSocket 和基于消息的 STOMP 端点,以实现实时通信。
⑩:***点对点通信-convertAndSendToUser ***,convertAndSendToUser 方法允许你向指定的用户发送消息,这是一种点对点通信的方式。你可以指定用户名和目标路径,以便将消息发送到特定用户的特定目标。如图,向名为 “ron.yu” 的用户发送了一条消息,目标路径为 “/queue/private”,这是一种点对点通信。
***广播通信-convertAndSend ***,convertAndSend 方法允许你向指定的主题广播消息,这是一种一对多通信的方式。多个订阅了相同主题的客户端都将收到该消息。使用 convertAndSend 方法向主题 “/topic/greetings” 广播了一条消息,这是一种广播通信。

五、什么是websocket的端点?

WebSocket 端点(WebSocket Endpoint)是 WebSocket 通信的入口点或终端。它是客户端和服务器之间建立 WebSocket 连接的目标位置,充当了通信的起点和终点。WebSocket 端点定义了 WebSocket 通信的具体位置和协议细节。
WebSocket 端点通常具有一个唯一的名称或路径,客户端可以使用这个名称或路径来建立与端点的连接。例如,一个 WebSocket 端点的路径可以是 “/chat”,客户端可以通过 WebSocket 连接到 “ws://example.com/chat” 来与该端点通信。

总结

这些代码只是简单实现了websocket的不同用户消息推送,并没有做权限检验复杂的功能。
刚写websocket,还是去官网找文档效率更高。文章来源地址https://www.toymoban.com/news/detail-730510.html

到了这里,关于websocket使用案例(前后端springboot+vue)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月11日
    浏览(50)
  • Spring Boot进阶(48):SpringBoot之集成WebSocket及使用说明 | 超级详细,建议收藏

            WebSocket是一种新型的通信协议,它可以在客户端与服务器端之间实现双向通信,具有低延迟、高效性等特点,适用于实时通信场景。在SpringBoot应用中,集成WebSocket可以方便地实现实时通信功能,如即时聊天、实时数据传输等。         本文将介绍如何在Sprin

    2024年02月16日
    浏览(40)
  • Spring Boot整合WebSocket实现实时通信,前端实时通信,前后端实时通信

    实时通信在现代Web应用中扮演着越来越重要的角色,无论是在线聊天、股票价格更新还是实时通知,WebSocket都是实现这些功能的关键技术之一。Spring Boot作为一个简化企业级应用开发的框架,其对WebSocket的支持也非常友好。本文将详细介绍如何在Spring Boot中整合WebSocket,实现一

    2024年04月27日
    浏览(31)
  • spring boot + mybatis + websocket + js实战

    项目技术:spring boot + mybatis + websocket + js 需求背景:当添加一个女孩时,页面的socket收到消息,打印最新的所有女生list,这样可以进一步在react/vue前端框架下,实现当A用户新增了某业务数据后,B用户的该业务list页面能自动将最新的业务数据list清单刷新出来,而不是需要点

    2024年01月25日
    浏览(33)
  • 基于SpringBoot+WebSocket+Spring Task的前后端分离外卖项目-订单管理(十七)

    1.1 介绍 Spring Task 是Spring框架提供的任务调度工具,可以按照约定的时间自动执行某个代码逻辑。 定位 :定时任务框架 作用 :定时自动执行某段Java代码 应用场景: 1). 信用卡每月还款提醒 2). 银行贷款每月还款提醒 3). 火车票售票系统处理未支付订单 4). 入职纪念日为用户发

    2024年02月21日
    浏览(38)
  • spring boot学习第六篇:SpringBoot 集成WebSocket详解

    1、WebSocket简介 WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。 2、为什么需要WebSocket HTTP 是基于请求响应式的,即通信只能由客户端发起,服务端做出响应,无状态,无连接。 无状态:每次连

    2024年01月21日
    浏览(40)
  • Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【三】

    😀前言 本篇博文是关于Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【三】的分享,希望你能够喜欢 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉 💕欢迎大家:这里是CSDN,我总结知识的地

    2024年02月11日
    浏览(36)
  • Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【一】

    😀前言 本篇博文是关于Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【一】,希望你能够喜欢 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉 💕欢迎大家:这里是CSDN,我总结知识的地方,欢

    2024年02月11日
    浏览(33)
  • Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【五】

    😀前言 本篇博文是关于Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【五】,希望你能够喜欢 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉 💕欢迎大家:这里是CSDN,我总结知识的地方,欢

    2024年02月10日
    浏览(35)
  • Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【二】

    😀前言 本篇博文是关于Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【二】的,希望你能够喜欢 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动力😉😉 💕欢迎大家:这里是CSDN,我总结知识的地方,

    2024年02月11日
    浏览(33)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包