Migrating existing Spring Websocket handler to use rsocket

别说谁变了你拦得住时间么 提交于 2020-04-30 09:28:50

问题


Suppose I have this simple Websocket handler for chat messages:

@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {
    webSocketSession
            .receive()
            .map(webSocketMessage -> webSocketMessage.getPayloadAsText())
            .map(textMessage -> textMessageToGreeting(textMessage))
            .doOnNext(greeting-> greetingPublisher.push(greeting))
            .subscribe();
    final Flux<WebSocketMessage> message = publisher
            .map(greet -> processGreeting(webSocketSession, greet));
    return webSocketSession.send(message);
}

What is needed to be done here in general as such it will use the rsocket protocol?


回答1:


RSocket controller in the Spring WebFlux looks more like a RestController than WebSocketHandler. So the example above is simple like that:

@Controller
public class RSocketController {

    @MessageMapping("say.hello")
    public Mono<String> saHello(String name) {
        return Mono.just("server says hello " + name);
    }
}

and this is equivalent to requestResponse method.

If this answer doesn't satisfy you, please describe more what you want to achieve.

EDIT

If you want to broadcast messages to all clients, they need to subscribe to the same Flux.

public class GreetingPublisher {

    final FluxProcessor processor;
    final FluxSink sink;

    public GreetingPublisher() {
        this.processor = DirectProcessor.<String>create().serialize();
        this.sink = processor.sink();
    }

    public void addGreetings(String greeting) {
        this.sink.next(greeting);
    }

    public Flux<String> greetings() {
        return processor;
    }
}

@Controller
public class GreetingController{

    final GreetingPublisher greetingPublisher = new GreetingPublisher();

    @MessageMapping("greetings.add")
    public void addGreetings(String name) {
        greetingPublisher.addGreetings("Hello, " + name);
    }

    @MessageMapping("greetings")
    public Flux<String> sayHello() {
        return greetingPublisher.greetings();
    }
}

Your clients have to call the greetings endpoint with the requestStream method. Wherever you send the message with the greetingPublisher.addGreetings() it's going to be broadcasted to all clients.



来源:https://stackoverflow.com/questions/61460983/migrating-existing-spring-websocket-handler-to-use-rsocket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!