【问题标题】:Send message to client on connect via Spring Websocket通过 Spring Websocket 在连接时向客户端发送消息
【发布时间】:2018-04-23 11:44:26
【问题描述】:

好的,我几乎已经阅读了 spring websocket 上的每一篇 stackoveflow 帖子。 我想在特定客户端连接到服务器后向它发送消息,很简单!

我已经能够从客户端进行连接,并且可以在服务器端监听新的连接。但是当我尝试从服务器端发送消息时,什么也没有发生。即使我的客户已经订阅了。

下面是我的客户端js。

var stompClient = null;
$(document).ready(function() {
    connect();
});

function connect() {
var socket = new SockJS('/context_path/stockfeeds');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/share', function(message) {
        console.log("Subscription successful............");
        console.log(JSON.parse(message.body));
    });

    stompClient.subscribe('/user/queue/reply', function(message) {
        console.log("Subscribed to user ...");
    });
}, function (error) {
    console.log("Stomp protocol error: "+ error);
});
}

$('#livetext').click(function () {
    stompClient.send('/app/stockfeeds', {}, 'This is BS');
});

当我单击“#livetext”时,发送发送功能起作用。并在客户端收到响应。 下面是我的控制器。

@Controller
public class StockDispatchController {

    @Autowired
    LoggerService loggerService;

    @MessageMapping("/stockfeeds")
    @SendTo("/topic/share")
    public String fetchStocks(String message) throws Exception {
        loggerService.info("-----------------------------"+ message);

        return message;
    }

}

下面是我的 Connect 事件监听器

import org.springframework.messaging.simp.SimpMessagingTemplate;

@Component
public class StompConnectEvent implements ApplicationListener<SessionConnectEvent> {

@Autowired
LoggerService logger;

@Autowired
private SimpMessagingTemplate messagingTemplate;

public void onApplicationEvent(SessionConnectEvent event) {

    this.messagingTemplate.convertAndSend("/topic/share", "A new client just connected");
    this.messagingTemplate.convertAndSendToUser(event.getUser().getName(), "/queue/reply", "I just connected");
    logger.info("message template sent");
}

}

当一个新的客户端连接时,事件监听器被触发并运行到最后,但我没有在客户端得到任何响应。

最后,下面是我的应用上下文 xml

<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/stockfeeds">
        <websocket:handshake-interceptors>
            <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
        </websocket:handshake-interceptors>
        <websocket:sockjs/>
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue"/>
</websocket:message-broker>

【问题讨论】:

    标签: stomp spring-websocket


    【解决方案1】:

    我还没有找到解决方案,但我找到了可行的替代方案。因此,我没有监听 SessionConnectedEvent,而是添加了一个控制器方法,当用户订阅它时会触发它。

    见下文。

    @SubscribeMapping("/reply")
    public String initialReply() throws Exception {
        return "Welcome to the chat room.";
    }
    

    我订阅它如下。

    stompClient.subscribe('/app/reply', function(message) {
        alert(message.body);
    });
    

    【讨论】:

      【解决方案2】:

      我有类似的用例,这就是我成功实现的。

      1. 您可以在客户端创建一些随机字符串,例如 clientId23,您可以通过已建立的 websocket 将其发送到服务器。
      2. 在订阅 URL 中添加相同的随机字符串,例如 /app/reply/clientId23
      3. 在服务器端,您可以将该 clientId 保存在 db 或其他东西中。使用它您可以向该特定客户端发送消息,例如this.messagingTemplate.convertAndSend("/app/reply/clientId23", "A new client just connected");

      编码愉快!

      【讨论】:

        【解决方案3】:

        这里已经很晚了,但以防万一有人需要这个。我没有使用对我不起作用的SessionConnectEvent,而是在阅读了文档后使用了SessionSubscribeEvent,它起作用了。

        @Component
        public class StompConnectEvent implements ApplicationListener<SessionSubscribeEvent> {
        
        @Autowired
        private SimpMessagingTemplate messagingTemplate;
        
        public void onApplicationEvent(SessionSubscribeEvent event) {
        
            this.messagingTemplate.convertAndSend("/topic/share", messageObject);
        
            }
        }
        

        一旦客户端订阅了 websocket 端点,SessionSubscribeEvent 就会被调用,因此它可以接收服务器发送到端点的消息。但是 SessionConnectEvent 在客户端最初尝试连接 websocket 时被调用,因此客户端还没有监听端点。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-05
          • 2017-09-30
          • 1970-01-01
          • 1970-01-01
          • 2020-07-10
          • 2021-07-18
          • 1970-01-01
          • 2012-01-18
          相关资源
          最近更新 更多