在 SockJsClient 中握手后无法发送消息(React)

Cannot send message after handshake in SockJsClient (React)

我正在使用 Spring Boot-React JS 并尝试通过 WebSocket 发送消息。握手很好,我可以毫无问题地订阅。当我尝试将数据发送到主题时,不起作用。 onMessage 没有被触发。

WebSocketConfig

   @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {

        // prefix for server to client message destination
        registry.enableSimpleBroker("/ws-push-notification"); 
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        // SockJS connection endpoint
        registry.addEndpoint("/ws-push-notifications").setAllowedOrigins(allowedOrigin).withSockJS();
    }

WebSocketDispatcher

 public void pushNotification(String pushToken, PushNotificationDto notificationDto) {

        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(pushToken);
        headerAccessor.setLeaveMutable(true);

        template.convertAndSendToUser(pushToken, "/ws-push-notification/item/" + pushToken,
                notificationDto, headerAccessor.getMessageHeaders());
    }

我检查了数据和令牌,是匹配的。

反应部分:

 const Client = ({
                              props,
                              autoReconnect = true
                          }) => {
    
        const url = "http://localhost:8080/ws-push-notifications?access_token=" + localStorage.getItem(STORAGE_KEY_AT);
        
       const topic = "ws-push-notification/item/" + props.pushToken;
   
        const headers = {
            "Content-Type": CONTENT_TYPE_JSON,
            Authorization: "Bearer " + localStorage.getItem(STORAGE_KEY_AT)
        };
    
        const onConnect = () => {
            props.changeSocketConnectionStatus(true);
            console.info(`Subscribed to socket ${SUDate.toISOLocalDateTime(new Date())}`);
        };
    
        const onMessage = (data) => {
            console.log("This part not getting triggered!!!")
        };

        return (
            <SockJsClient
                url={url}
                topics={[topic]}
                headers={headers}
                subscribeHeaders={headers}
                onConnect={onConnect}
                onMessage={onMessage}
                onDisconnect={onDisconnect}
                onConnectFailure={onConnectFailure}
                autoReconnect={autoReconnect}
            />
        );
    };
    
    export default Client;

template.convertAndSendToUser(pushToken, "/ws-push-notification/item/" + pushToken, notificationDto, headerAccessor.getMessageHeaders());

这会将 dto 发送到: /ws-push-notification/item/771063a4-fcea-454f-9673-dedc842290bb905557640

这部分在这里是一样的。 const topic = "ws-push-notification/item/" + props.pushToken;

为什么不起作用?

问题是没有接收到数据。正在发送。

template.convertAndSend("/ws-push-notification/item/" + pushToken, notificationDto);

解决了我的问题。