欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > vue3+websocket+springboot、websocket消息通讯

vue3+websocket+springboot、websocket消息通讯

2025/2/11 13:04:49 来源:https://blog.csdn.net/qq_39933800/article/details/145529452  浏览:    关键词: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 {@Overridepublic 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 {@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {// 连接建立后的逻辑System.out.println(session.getId());}@Overrideprotected 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就可以给那个专门的客户端发送消息了。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com