在Spring框架中,我们可以使用@EnableWebSocketMessageBroker注解来配置一个WebSocket消息代理。这个代理可以用于创建一个端点,我们可以在客户端和服务器之间发送和接收消息。
以下是一个简单的例子,展示了如何在Spring Boot应用程序中配置和使用WebSocket:
- 在Spring Boot应用程序中添加Spring WebSocket依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>- 配置WebSocket消息代理:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
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");
    }
 
    @Controller
    public class WebSocketController {
        @MessageMapping("/hello")
        @SendTo("/topic/greetings")
        public Greeting greeting(HelloMessage message) throws Exception {
            return new Greeting("Hello, " + message.getName() + "!");
        }
    }
}在这个配置中,我们定义了一个WebSocket端点/ws,它使用SockJS来兼容不同的浏览器。我们还定义了一个简单的消息代理,它将在前缀/topic下广播消息,并在前缀/app下处理标注了@MessageMapping的消息。
客户端可以通过WebSocket连接到这个端点,并通过/app/hello发送消息,然后通过/topic/greetings接收消息。
这只是一个简单的例子,实际应用中可能需要更复杂的配置和安全设置。