import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class EchoHandler implements WebSocketHandler {

@Override
public Mono<Void> handle(WebSocketSession session) {
    AtomicReference<Disposable> subscriptionRef = new AtomicReference<>();

    return session.receive()
            .doOnNext(message -> {

                // Cancel old Flux if it exists
                Disposable oldSubscription = subscriptionRef.getAndSet(null);
                if (oldSubscription != null)
                    oldSubscription.dispose();

                // Start a new Flux with the new message
                Disposable subscription = Flux.interval(Duration.ofSeconds(1))
                        .map(seq -> session.textMessage(message.getPayloadAsText() + "-" + seq))
                        .doFinally(signalType -> subscriptionRef.compareAndSet(subscription, null))
                        .subscribe(
                            session::send,
                            error -> {/* handle error here */} 
                        );

                // Save the new subscription so it can be cancelled if a new message is received
                subscriptionRef.set(subscription);
            })
            .then();
}

}


极品公子
221 声望43 粉丝

山不向我走来,我便向山走去。