RuF
RuF

Reputation: 558

How can I send message to the specific clients via websockets in Spring Webflux?

I developed web chat with ReactJS\redux in Client and spring-boot-starter-webflux\Reactor\Spring Boot 2 in Server.

Server developed like here.

Clint receives the messages that way:

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);
    }

One message will be send to all clients. How can I send message to the specific clients via websockets? Not for all.

I found some giudes with SockJS, but I want to use Spring Webflux\Reactor.

UPDATE:

I have the following configuration in server:

@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;
}

So I send message to the /websocket/chat path from the client.

Can I set up this path to Client1 send message to /websocket/chat/chat1 and Client2 send message to /websocket/chat/chat2? So /websocket/chat/chat1 and /websocket/chat/chat2 are different chats.

For example, Client1 and Client3 recive the messages of /websocket/chat/chat1, but they does not recive messages of /websocket/chat/chat2?

Number of the chats can change dynamically depending on the clients activity.

Upvotes: 2

Views: 2738

Answers (1)

markusw
markusw

Reputation: 2055

Websocket is a Client-Server protocol, so a sending from a client to another client is only doable via the server as the mediator. What you need to accomplish is to implement a fuctionality at the server, that if a specific message (e.g. special custom header information) is received, you need to dispatch that to the corresponding client (e.g. client-ID).

Sending a Websocket from a client directly to another client is not possible because of the protocol.

There are several convertAndSendToUser(..) methods available in the Spring WebSocketTemplate. Have a look at this answer. It describes the way in very detail.

Upvotes: 1

Related Questions