首页 > 解决方案 > 在 Spring Boot 和 Angular 中使用 websockets 向客户端发送触发器

问题描述

我想从后端(基于spring boot)向userId为xyz的特定用户启动触发器(可能是通知)。

我发现的一种方法是:

最初我连接到 websocket 端点并订阅频道“/user/Notifications/xyz”以下是我的角度打字稿中的相关代码

connectToUserWebSocket(userId) {
        let socket = new SockJS('http://localhost:5000/fellowGenius');
        this.ws = Stomp.over(socket);
        let that = this;
        this.ws.connect(
          {},
          (frame) => {
            that.ws.subscribe('/user/Notifications/' +userId, (message) => {
            console.log("user subscribed");
            });
    
          },
          (error) => {
            alert('STOMP error ' + error);
          }
        );
        
    }

现在一旦我订阅了我的频道。我想向客户端发送一个由后端本身启动的触发器,因此我在我的 java 服务中运行代码。我的相关java代码是:

@SendTo("/user/Notifications/{userId}")
    public String sendMeetingNotificationWebSocket(@DestinationVariable String userId) {
        return "hello";
    }

我的 websocket 配置是:

@Configuration      
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/fellowGenius").setAllowedOrigins("*").addInterceptors(new HttpSessionHandshakeInterceptor()).withSockJS();
        }
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/inbox/","/user/Notifications/");
        }
}

但问题是,即使我可以看到在我的 Spring Boot 控制台中连接了一个 Web 套接字。但我没有得到客户端功能的响应。

请帮我解决这个问题。

标签: javaangularspringspring-bootspring-websocket

解决方案


推荐阅读