springboot + vue websocket
时间: 2023-12-23 18:27:33 浏览: 166
以下是使用Spring Boot和Vue.js实现WebSocket的示例:
1. 在Spring Boot中配置WebSocket:
```java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
```
2. 在Vue.js中使用WebSocket:
```javascript
mounted() {
// 连接WebSocket
const socket = new SockJS('/websocket');
const stompClient = Stomp.over(socket);
// 监听消息
stompClient.connect({}, () => {
stompClient.subscribe('/topic/messages', (message) => {
console.log(message.body);
});
});
},
methods: {
// 发送消息
sendMessage() {
stompClient.send("/app/sendMessage", {}, "Hello, WebSocket!");
}
}
```
阅读全文