当前位置: 首页 > article >正文

vue3+websocket+springboot、websocket消息通讯

websocket 通信

后端

后端-配置类:

package com.yupi.project.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}

后端-消息处理类:

package com.yupi.project.config;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后的逻辑
        System.out.println(session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理收到的消息
        System.out.println("Received message from client [" + session.getId() + "]: " + message.getPayload());

        // 回送消息给客户端
        String echoMessage = "Echo: " + message.getPayload()+",session id is"+session.getId();
        TextMessage returnMessage = new TextMessage(echoMessage);
        session.sendMessage(returnMessage);

        System.out.println("Sent message to client [" + session.getId() + "]: " + returnMessage.getPayload());
    }
}

前端

前端测试页面代码:
进入页面后,会自动建立一个websocket连接

<template>
  <div>
    123
    <!-- Your component template -->
    <button @click="sendMessage">发送消息</button>
  </div>
</template>

<script>
import { webSocketService } from '@/services/webSocketService';

export default {
  name: 'YourComponentName',
  data() {
    return {
      message: '',
      authToken: 'your-auth-token-here' // 请替换为实际的token获取逻辑
    };
  },
  mounted() {
    webSocketService.connect(this.authToken);
  },
  beforeUnmount() {
    webSocketService.disconnect();
  },
  methods: {
    sendMessage() {
      webSocketService.sendMessage(JSON.stringify({ message: '12345678' }));
    }
  }
};
</script>

前端js代码

// src/services/webSocketService.js
export const webSocketService = {
    socket: null,
    connect(authToken) {
        // 注意:这里的URL应根据实际情况调整
        //this.socket = new WebSocket(`ws://${location.hostname}:${location.port}/api/ws`);
        this.socket = new WebSocket('ws://localhost:5173/api/ws');// 代理地址
        // 发送认证信息
        this.socket.onopen = () => {
            this.socket.send(JSON.stringify({
                type: 'auth',
                token: authToken // 这里假设使用token进行认证
            }));
        };

        this.socket.onmessage = (event) => {
            console.log('服务度返回的消息 ', event.data);
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket error: ', error);
        };
    },
    sendMessage(message) {
        console.log("this.socket")
        console.log(this.socket)
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(message);
            console.log('已发送消息')
        }
    },
    disconnect() {
        if (this.socket) {
            this.socket.close();
        }
    }
};

前端代理:

  // 配置服务器的代理设置
  server: {
    // 代理配置,用于重定向请求到其他服务器
    proxy: {
      '/api': {
        target: 'ws://localhost:7529',//后端tomcat端口
        ws: true, // 开启WebSocket代理
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, 'api')
      }
    }
  }

结果:
在这里插入图片描述
拓展:
1、消息发送后还没有关闭,前后端如何关闭?
2、如何广播消息?
3、利用session id 来对不同的客户端连接发送消息?只需要带着session id就可以给那个专门的客户端发送消息了。


http://www.kler.cn/a/541053.html

相关文章:

  • JVM做GC垃圾回收时需要多久,都由哪些因素决定的
  • 手写一个C++ Android Binder服务及源码分析
  • 【动态规划篇】:动态规划解决路径难题--思路,技巧与实例
  • MATLAB中extract 函数用法
  • Go语言构建微服务:从入门到实战
  • 保姆级教程Docker部署Zookeeper模式的Kafka镜像
  • 2025.2.8——二、Confusion1 SSTI模板注入|Jinja2模板
  • DWORD 和 QWORD
  • yum报错 Could not resolve host: mirrorlist.centos.org
  • HarmonyOS开发 - 记事本实例一(界面搭建)
  • 如何利用 AWS 预测分析功能做精准财务规划?
  • C++ STL Map 学习学案(提高版)
  • java-LinkedList源码详解
  • 本地部署DeepSeek-R1(Mac版)
  • keil5自学笔记1(基础设置)
  • RapidrepairDaoImpl
  • 利用ES6 Set去重
  • 标题:深入探索 gRPC:后端开发中高效通信的利器
  • Python语言的数据可视化
  • 2025年一段代码使用python完成过年放烟花写祝福
  • 【多模态大模型】系列2:如何用多GPU训练一个非常大的模型(数据/模型/流水线/张量并行、MoE、混合精度训练、压缩、激活重新计算)
  • elementplus 使用日期时间选择器,设置可选范围为前后大于2年且只能选择历史时间不能大于当前时间点
  • DeepSeek大模型的发展的十问十答
  • 蓄电池放电技术革新:引领能源存储新时代
  • Day60_补20250208_图论part5_并查集理论基础|寻找存在的路径
  • C++ 中的 cJSON 解析库:用法、实现及递归解析算法与内存高效管理