【SpringBoot】SpringBoot:构建实时聊天应用
要在Spring Boot中构建实时聊天应用,你可以使用WebSocket。以下是一个简单的例子,展示了如何使用Spring Boot和WebSocket来构建一个基本的实时聊天应用。
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocket:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
}
- 创建消息控制器:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class ChatController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(ChatMessage message) {
return message;
}
}
- 创建消息实体类:
public class ChatMessage {
private String content;
private String sender;
// Getters and setters
}
- 前端使用WebSocket发送和接收消息:
const socket = new WebSocket('ws://' + window.location.host + '/ws');
socket.onopen = function(event) {
console.log('WebSocket connected');
};
socket.onmessage = function(event) {
console.log('Received message: ' + event.data);
};
function sendMessage(message) {
socket.send(JSON.stringify({
destination: "/app/chat.sendMessage",
content: message
}));
}
socket.onclose = function(event) {
console.log('WebSocket closed');
};
socket.onerror = function(event) {
console.error('WebSocket error observed:', event);
};
确保你的前端JavaScript代码连接到正确的WebSocket端点,并且在发送和接收消息时遵循你的应用程序的路径和协议。
这个简单的例子展示了
评论已关闭