springboot+vue实现聊天功能代码
时间: 2023-11-11 18:02:34 浏览: 104
这是一个简单的Spring Boot + Vue.js实现聊天功能的代码示例,使用WebSocket实现实时通信。
后端代码:
```
// ChatMessage.java
public class ChatMessage {
private String sender;
private String content;
// getters and setters
}
// ChatController.java
@RestController
public class ChatController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@MessageMapping("/chat")
public void sendMessage(@Payload ChatMessage message) {
messagingTemplate.convertAndSend("/topic/messages", message);
}
}
// WebSocketConfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
```
前端代码:
```
<!-- Chat.vue -->
<template>
<div>
<input v-model="message" @keyup.enter="sendMessage">
<ul>
<li v-for="message in messages">{{ message }}</li>
</ul>
</div>
</template>
<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {
data() {
return {
message: '',
messages: []
};
},
mounted() {
const socket = new SockJS('/chat');
const stompClient = Stomp.over(socket);
stompClient.connect({}, frame => {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', message => {
this.messages.push(JSON.parse(message.body));
});
});
},
methods: {
sendMessage() {
const message = {
sender: 'me',
content: this.message
};
this.messages.push(message);
const socket = new SockJS('/chat');
const stompClient = Stomp.over(socket);
stompClient.connect({}, frame => {
console.log('Connected: ' + frame);
stompClient.send('/app/chat', {}, JSON.stringify(message));
});
this.message = '';
}
}
};
</script>
```
这个示例使用了SockJS和Stomp.js来与服务器进行WebSocket通信。在mounted()函数中创建了WebSocket连接,并订阅了/topic/messages主题,以便接收服务器发送的消息。sendMessage()方法将用户输入的消息发送到服务器,并将其添加到消息列表中。
阅读全文