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();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。