【问题标题】:How can I send message to the specific clients via websockets in Spring Webflux?如何通过 Spring Webflux 中的 websockets 向特定客户端发送消息?
【发布时间】:2018-09-26 04:34:40
【问题描述】:

我在 Client 中使用 ReactJS\redux 和在 Server 中使用 spring-boot-starter-webflux\Reactor\Spring Boot 2 开发了网络聊天。

服务器开发类似于here

Clint 以这种方式接收消息:

this.clientWebSocket = new WebSocket("ws://127.0.0.1:8080/websocket/chat");
this.clientWebSocket.onopen = function() {
    }
    this.clientWebSocket.onclose = function() {
    }
    this.clientWebSocket.onerror = function() {
    }
    var _this = this;
    this.clientWebSocket.onmessage = function(dataFromServer) {
        _this.updateMessages(dataFromServer);
    }

一条消息将发送给所有客户端。 我如何通过 websockets 向特定的客户端发送消息? 并非全部。

我找到了一些关于 SockJS 的指南,但我想使用 Spring Webflux\Reactor。

更新:

我在服务器中有以下配置:

@Bean
public HandlerMapping webSocketMapping(UnicastProcessor<Event> eventPublisher, Flux<Event> events) {
    Map<String, Object> map = new HashMap<>();
    map.put("/websocket/chat", new ChatSocketHandler(eventPublisher, events));
    SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
    simpleUrlHandlerMapping.setUrlMap(map);

    simpleUrlHandlerMapping.setOrder(10);
    return simpleUrlHandlerMapping;
}

所以我从客户端向 /websocket/chat 路径发送消息。

我可以设置这条路径让 Client1 向 /websocket/chat/chat1 发送消息,Client2 向 /websocket/chat/chat2 发送消息吗?所以 /websocket/chat/chat1/websocket/chat/chat2 是不同的聊天。

例如Client1和Client3收到/websocket/chat/chat1的消息,却没有收到/websocket/chat/chat2的消息? p>

聊天的数量可以根据客户的活动动态变化。

【问题讨论】:

    标签: java reactjs spring-websocket spring-webflux project-reactor


    【解决方案1】:

    Websocket 是一个客户端-服务器协议,所以从一个客户端到另一个客户端的发送只能通过服务器作为中介。您需要完成的是在服务器上实现一个功能,如果收到特定消息(例如特殊的自定义标头信息),您需要将其分派给相应的客户端(例如客户端 ID)。

    由于协议的原因,无法从客户端直接向另一个客户端发送 Websocket。

    Spring WebSocketTemplate 中有几个convertAndSendToUser(..) 方法可用。看看this answer。它非常详细地描述了这种方式。

    【讨论】:

    • 感谢您的回复。请参阅我更新的问题。我想不明白如何“将其发送给相应的客户(例如客户 ID)”
    • 请注意,您链接的方法适用于 Stomp 协议,反应式 websockets 似乎不使用该协议。
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 2022-07-01
    • 2014-12-31
    • 2020-07-17
    • 2016-09-19
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多