SpringBoot(java)实现websocket实现实时通信
在Spring Boot中实现WebSocket的实时通信,你可以使用Spring的@EnableWebSocketMessageBroker
注解来配置WebSocket,并且创建一个控制器来处理WebSocket的消息。
以下是一个简单的例子:
- 添加Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 配置WebSocketMessageBroker:
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");
}
}
- 创建WebSocket控制器:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class WebSocketController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public.messages")
public ChatMessage sendMessage(ChatMessage message) {
return message;
}
}
class ChatMessage {
private String content;
// getters and setters
}
在这个例子中,客户端可以通过连接到/ws
端点来建立WebSocket连接,并且可以发送消息到服务器,服务器将这些消息广播到所有连接的客户端。
确保你的ChatMessage
类有合适的getter和setter方法,以便能够被Spring的消息转换器序列化和反序列化。
评论已关闭