Spring: send message to websocket clients

前端 未结 1 774
旧巷少年郎
旧巷少年郎 2021-02-06 09:50

I\'m building a webchat with Spring Boot, RabbitMQ and WebSocket as POC, but I\'m stucked a the last point: WebSockets
I want my ws clients to connect to a specific endpoint

1条回答
  •  佛祖请我去吃肉
    2021-02-06 10:28

    Ok, I think I got it, for everyone who needs it, here is the answer:

    first, you need to add WS dependencies to the pom.xml

    
        org.springframework.boot
        spring-boot-starter-websocket
    
    
        org.springframework
        spring-messaging
    
    

    create a WS endpoint

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            // the endpoint for websocket connections
            registry.addEndpoint("/stomp").withSockJS();
        }
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/");
    
            // use the /app prefix for others
            config.setApplicationDestinationPrefixes("/app");
        }
    
    }
    

    Note: I'm using STOMP, so the clients should connect like this

    
    

    Then, you can simply wire the ws messenger on your components with

    @Autowired
    private SimpMessagingTemplate webSocket;
    

    and send the message with

    webSocket.convertAndSend(channel, new String(message.getBody()));
    

    0 讨论(0)
提交回复
热议问题