如何在Spring Webflux中通过websocket向特定客户端发送消息?

时间:2019-03-04 10:30:32

标签: spring websocket spring-webflux

我是Spring Webflux的新手。我想在春季实施websocket应用程序。有人可以帮我吗,我该如何向所有连接的客户端中的特定客户端发送消息。

服务器代码

private void serverLogic(WebSocketSessionHandler sessionHandler, long interval)
{
    sessionHandler
        .connected()
        .subscribe(session -> logger.info("Client Connected [{}]", session.getId()));

    sessionHandler
        .disconnected()
        .subscribe(session -> logger.info("Client Disconnected [{}]", session.getId()));

    Flux<String> receiveAll =
        sessionHandler
            .receive()              
            .subscribeOn(Schedulers.elastic())
            .doOnNext(message -> logger.info("Server Received: [{}]", message));

    Mono<String> receiveFirst =
        sessionHandler
            .receive()
            .subscribeOn(Schedulers.elastic())
            .next();


    //This module is sending data to all the clients that are connected. How do I alter this one?

    Flux<String> send =
        Flux
            .interval(Duration.ofMillis(interval))
            .subscribeOn(Schedulers.elastic())              
            .takeUntil(value -> !sessionHandler.isConnected())
            .map(value -> Long.toString(value))
            .doOnNext(message -> sessionHandler.send(message))
            .doOnNext(message -> logger.info("Server Sent: [{}]", message));

    receiveAll.subscribe();
    receiveFirst.thenMany(send).subscribe();
}

0 个答案:

没有答案