springboot+vue+websocket实现聊天室代码实现
时间: 2023-06-12 16:08:24 浏览: 295
基于springboot+WebSocket聊天室项目
以下是一个简单的使用Spring Boot、Vue.js和WebSocket实现的聊天室的代码示例:
Spring Boot后端代码:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/chat").setAllowedOrigins("*");
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
class WebSocketHandler extends TextWebSocketHandler {
private static final Map<WebSocketSession, String> users = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) {
users.put(session, "Anonymous");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
ChatMessage chatMessage = new ObjectMapper().readValue(message.getPayload(), ChatMessage.class);
if (chatMessage.getType() == ChatMessage.MessageType.JOIN) {
users.put(session, chatMessage.getSender());
}
for (WebSocketSession user : users.keySet()) {
user.sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(chatMessage)));
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
users.remove(session);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class ChatMessage {
public enum MessageType {
CHAT, JOIN, LEAVE
}
private String sender;
private String content;
private MessageType type;
public static ChatMessage joinMessage(String sender) {
return new ChatMessage(sender, "", MessageType.JOIN);
}
public static ChatMessage leaveMessage(String sender) {
return new ChatMessage(sender, "", MessageType.LEAVE);
}
}
@RestController
public class ChatController {
@GetMapping("/users")
public List<String> users() {
return new ArrayList<>(WebSocketHandler.users.values());
}
}
```
Vue.js前端代码:
```html
<template>
<div>
<h2>Chat Room</h2>
<div>
<label>Your name:</label>
<input v-model="name" @keyup.enter="join" />
<button @click="join">Join</button>
</div>
<div v-if="joined">
<div>
<label>Message:</label>
<input v-model="message" @keyup.enter="send" />
<button @click="send">Send</button>
</div>
<div>
<h3>Users:</h3>
<ul>
<li v-for="user in users" :key="user">{{ user }}</li>
</ul>
</div>
<div>
<h3>Chat:</h3>
<ul>
<li v-for="chat in chats" :key="chat.id">
<strong>{{ chat.sender }}:</strong> {{ chat.content }}
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
import SockJS from "sockjs-client";
import Stomp from "stompjs";
export default {
data() {
return {
name: "",
message: "",
joined: false,
chats: [],
users: [],
stompClient: null,
};
},
methods: {
join() {
const socket = new SockJS("/chat");
this.stompClient = Stomp.over(socket);
this.stompClient.connect({}, () => {
this.stompClient.subscribe("/topic/chat", (message) => {
const chat = JSON.parse(message.body);
if (chat.type === "JOIN") {
this.users.push(chat.sender);
} else if (chat.type === "LEAVE") {
this.users.splice(this.users.indexOf(chat.sender), 1);
}
this.chats.push(chat);
});
this.stompClient.send(
"/app/chat",
JSON.stringify(ChatMessage.joinMessage(this.name))
);
this.joined = true;
});
},
send() {
this.stompClient.send(
"/app/chat",
JSON.stringify(
new ChatMessage(this.name, this.message, ChatMessage.MessageType.CHAT)
)
);
this.message = "";
},
},
};
class ChatMessage {
static MessageType = {
CHAT: "CHAT",
JOIN: "JOIN",
LEAVE: "LEAVE",
};
constructor(sender, content, type) {
this.sender = sender;
this.content = content;
this.type = type;
}
static joinMessage(sender) {
return new ChatMessage(sender, "", ChatMessage.MessageType.JOIN);
}
static leaveMessage(sender) {
return new ChatMessage(sender, "", ChatMessage.MessageType.LEAVE);
}
}
</script>
```
在这个示例中,我们使用了Spring Boot的WebSocket支持来处理来自客户端的事件。我们创建了一个WebSocket处理程序,它维护了一个用户会话列表,并在用户加入、离开或发送聊天消息时广播消息到所有连接的客户端。我们还为WebSocket处理程序创建了一个控制器,以便在客户端请求所有当前连接的用户列表时返回它们。
在Vue.js应用程序中,我们使用SockJS和Stomp.js来建立与服务器的WebSocket连接,并处理来自服务器的事件。我们使用Vue.js的数据绑定来更新聊天消息、用户列表和用户输入框中的数据,并在加入聊天室、发送聊天消息或断开连接时发送相关的WebSocket事件。
阅读全文