写一段SpringBoot + Vue + websocket实现的一对一聊天代码
时间: 2023-09-18 10:16:21 浏览: 137
基于Springboot+Vue志同道合交友网站源码案例设计.zip
这里给出一个简单的SpringBoot + Vue + websocket实现的一对一聊天的代码示例。
后端代码(基于SpringBoot):
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer{
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ChatWebSocketHandler(), "/chat");
}
}
@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new ArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
session.sendMessage(new TextMessage("欢迎来到聊天室!"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions) {
if (s != session) {
s.sendMessage(new TextMessage(message.getPayload()));
}
}
}
}
```
前端代码(基于Vue):
```html
<template>
<div>
<div v-for="(message, index) in messages" :key="index">
{{ message }}
</div>
<input type="text" v-model="input" @keydown.enter="sendMessage" />
</div>
</template>
<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {
data() {
return {
input: '',
messages: [],
};
},
methods: {
connect() {
const socket = new SockJS('/chat');
this.stompClient = Stomp.over(socket);
this.stompClient.connect({}, (frame) => {
this.stompClient.subscribe('/topic/chat', (response) => {
this.messages.push(response.body);
});
});
},
disconnect() {
if (this.stompClient != null) {
this.stompClient.disconnect();
}
},
sendMessage() {
if (this.input !== '') {
this.stompClient.send('/app/chat', {}, this.input);
this.input = '';
}
},
},
created() {
this.connect();
},
beforeDestroy() {
this.disconnect();
},
};
</script>
```
在这个例子中,我们使用了SockJS和Stomp.js来实现websocket的客户端连接。在前端中,我们使用connect方法来连接到websocket,disconnect方法来断开连接,sendMessage方法来发送信息。在后端中,我们使用TextWebSocketHandler来处理websocket连接,afterConnectionEstablished方法用于建立连接,handleTextMessage方法用于处理收到的信息。
需要注意的是,这里的聊天室只支持一对多的聊天,如果需要实现一对一的聊天,需要在后端代码中对应修改。
阅读全文