一、
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
二、
配置WebSocket
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("*");
}
}
三、
创建WebSocket处理器
import org.springframework.web.socket.CloseStatus;
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 {
// 连接建立后,可以向客户端发送消息
session.sendMessage(new TextMessage("Connection established"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理收到的消息
String payload = message.getPayload();
System.out.println("Received message: " + payload);
session.sendMessage(new TextMessage("Message received: " + payload));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 连接关闭后的处理
}
}
四、
Vue使用WebSocket
<template>
<div id="app">
<h1>WebSocket Demo</h1>
<button @click="sendMessage">Send Message</button>
<p>{{ response }}</p>
</div>
</template>
<script>
export default {
data() {
return {
websocket: null,
response: ''
};
},
mounted() {
// 连接WebSocket服务器
this.websocket = new WebSocket('ws://localhost:8080/ws');
// 处理收到的消息
this.websocket.onmessage = (event) => {
this.response = event.data;
};
// 连接关闭的处理
this.websocket.onclose = () => {
console.log('WebSocket connection closed');
};
},
methods: {
sendMessage() {
if (this.websocket) {
this.websocket.send('Hello, server!');
}
}
}
};
</script>
<style scoped>
</style>