前端端口:9090
后端端口:8080
vue3
引入依賴:
npm install sockjs-client @stomp/stompjs
vue頁面
<template><div><h1>WebSocket 示例</h1><button @click="sendMessage">發送消息</button><div>{{ messages }}</div></div>
</template><script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import SockJS from "sockjs-client";
import { Stomp } from "@stomp/stompjs";const messages = ref();
let stompClient: any = null;//websocket連接
const connect = () => {const socket = new SockJS("http://localhost:8080/ws");stompClient = Stomp.over(socket);stompClient.connect({},(frame: string) => {console.log("Connected: " + frame);stompClient.subscribe("/topic/greetings", (message: { body: string }) => {console.log("Received: " + message.body);messages.value = message.body;//messages.value.push(message.body);});},(error: string) => {console.error("Error: " + error);});
};//發送消息
const sendMessage = () => {if (stompClient && stompClient.connected) {stompClient.send("/app/hello", {}, "hello, world");} else {console.error("No STOMP connection available");}
};onMounted(() => {connect();
});onBeforeUnmount(() => {if (stompClient) {stompClient.disconnect();}
});
</script><style scoped>
/* 添加你的樣式 */
</style>
springboot
引入依賴
<!-- Spring Boot WebSocket依賴 --><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;@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {@Overridepublic void configureMessageBroker(MessageBrokerRegistry config) {config.enableSimpleBroker("/topic"); // 使用內存中的簡單代理來廣播消息config.setApplicationDestinationPrefixes("/app"); // 客戶端發送消息到服務器的前綴}@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint("/ws").setAllowedOrigins("http://localhost:9090") // 允許的來源列表.withSockJS(); // 注冊 WebSocket 端點,并啟用 SockJS 備份傳輸方式}
}
controller
@MessageMapping("/hello")@SendTo("/topic/greetings")public String greeting(String message) {System.out.println(message);return "你好";}
測試
點擊按鈕
?另一個連接這個廣播主題的頁面也會接受到信息
后端控制臺
?
?===============================注意====================================
這里說明一下,假如vue文件里的onMounted將連接和發送兩個函數寫在一起,即:
onMounted(() => {
? connect();??sendMessage();
});
?你會發現sendMessage()里并沒有發送到后端,后端你也沒有返回消息。
原因:
異步性:WebSocket 連接是異步的。這意味著?connect
?函數會立即返回,而實際的連接過程會在之后發生。因此,如果您在?connect
?函數返回后立即調用?sendMessage
,stompClient
?可能還沒有被成功初始化,因為連接可能還沒有建立。