0

我有一个 spring websocket 项目并创建了一个非常基本的页面来测试它,一切似乎都工作正常,除了 UNSUBSCRIBE 消息的侦听器。

    @EventListener
    public void handleSessionSubscribeEvent(SessionSubscribeEvent event) {
        System.out.println("SUBSCRIBED " + event);
    }

    @EventListener
    public void handleSessionUnsubscribeEvent(SessionUnsubscribeEvent event) {
        System.out.println("UNSUBSCRIBED " + event);
    }

    @EventListener
    public void handleSessionDisconnectEvent(SessionDisconnectEvent event) {
        System.out.println("DISCONNECTED " + event);
    }

当前端进行订阅时,我从侦听器获得第一个打印,但是当它取消订阅时,不会触发侦听器。您可以在 Chrome 的 websocket 日志中看到 UNSUBSCRIBE 消息已发送:

["CONNECTED\nversion:1.1\nheart-beat:0,0\nuser-name:BsFJQRRyrKR4iUdSZyx0\n\n\u0000"]
["SUBSCRIBE\nid:666\ndestination:/topic/myTopic\n\n\u0000"]
["MESSAGE\ndestination:/topic/myTopic\ncontent-type:application/json\nsubscription:666\nmessage-id:hfxgxgci-4\ncontent-length:57\n\n{\"timestamp\":\"2021-08-04T14:34:22.157688Z\",\"value\":239.0}\u0000"]
["MESSAGE\ndestination:/topic/myTopic\ncontent-type:application/json\nsubscription:666\nmessage-id:hfxgxgci-4\ncontent-length:57\n\n{\"timestamp\":\"2021-08-04T14:34:22.157688Z\",\"value\":474.0}\u0000"]
["MESSAGE\ndestination:/topic/myTopic\ncontent-type:application/json\nsubscription:666\nmessage-id:hfxgxgci-4\ncontent-length:57\n\n{\"timestamp\":\"2021-08-04T14:34:22.157688Z\",\"value\":120.0}\u0000"]
["UNSUBSCRIBE\nid:666\n\n\u0000"]

这是我在订阅前端的代码:

const subscription = await WebSocketService.subscribe(`/topic/myTopic`);

这是我的退订代码:

return () => {
    batcher.clear();

    subscriptions.forEach((subscription) => {
        subscription.unsubscribe();
    });
};

正如您从 Chrome 日志中看到的那样,正在发送 UNSUBSCRIBE 消息,但我的侦听器没有触发。有任何想法吗 ?

4

0 回答 0