-
-
Save monkey-codes/cb45f3645f6b612a1107032cf5090d9d to your computer and use it in GitHub Desktop.
Connecting WebSocketSessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Override | |
| public Mono<Void> handle(WebSocketSession session) { | |
| WebSocketMessageSubscriber subscriber = new WebSocketMessageSubscriber(eventPublisher); | |
| session.receive() | |
| .map(WebSocketMessage::getPayloadAsText) | |
| .map(this::toEvent) | |
| .subscribe(subscriber::onNext, subscriber::onError, subscriber::onComplete); | |
| return session.send(outputEvents.map(session::textMessage)); | |
| } | |
| private static class WebSocketMessageSubscriber { | |
| private UnicastProcessor<Event> eventPublisher; | |
| private Optional<Event> lastReceivedEvent = Optional.empty(); | |
| public WebSocketMessageSubscriber(UnicastProcessor<Event> eventPublisher) { | |
| this.eventPublisher = eventPublisher; | |
| } | |
| public void onNext(Event event) { | |
| lastReceivedEvent = Optional.of(event); | |
| eventPublisher.onNext(event); | |
| } | |
| public void onError(Throwable error) { | |
| //TODO log error | |
| error.printStackTrace(); | |
| } | |
| public void onComplete() { | |
| lastReceivedEvent.ifPresent(event -> eventPublisher.onNext( | |
| Event.type(USER_LEFT) | |
| .withPayload() | |
| .user(event.getUser()) | |
| .build())); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment