tterrag1098

Untitled

Oct 21st, 2018
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. public class WebSocketClient<I, O> {
  2.  
  3. private final EmitterProcessor<I> receiver = EmitterProcessor.create(false);
  4. private final EmitterProcessor<O> sender = EmitterProcessor.create(false);
  5.  
  6. // initialize the sinks to safely produce values downstream
  7. // we use LATEST backpressure handling to avoid overflow on no subscriber situations
  8. private final FluxSink<I> receiverSink = receiver.sink(FluxSink.OverflowStrategy.LATEST);
  9. private final FluxSink<O> senderSink = sender.sink(FluxSink.OverflowStrategy.LATEST);
  10.  
  11. public Mono<Void> connect(@Nonnull String url, FrameParser<I, O> handler) {
  12. return Mono.defer(() -> {
  13. // Subscribe each inbound GatewayPayload to the receiver sink
  14. Disposable inboundSub = handler.inbound()
  15. .doOnError(t -> log.debug("Inbound encountered an error", t))
  16. .doOnCancel(() -> log.debug("Inbound cancelled"))
  17. .doOnComplete(() -> log.debug("Inbound completed"))
  18. .subscribe(receiverSink::next);
  19.  
  20. // Subscribe the receiver to process and transform the inbound payloads into Dispatch events
  21. Disposable receiverSub = receiver.log().doOnError(Throwable::printStackTrace).subscribe();
  22.  
  23. // Subscribe the handler's outbound exchange with our outgoing signals
  24. // routing error and completion signals to close the gateway
  25. Disposable senderSub = sender.log().subscribe(handler.outbound()::onNext, t -> { t.printStackTrace(); handler.close(); }, handler::close);
  26.  
  27. return HttpClient.create()
  28. .observe((connection, newState) -> log.debug("{} {}", newState, connection))
  29. .wiretap()
  30. .noCompression()
  31. .websocket()
  32. .uri(url)
  33. .handle(handler::handle)
  34. .doOnError(Throwable::printStackTrace)
  35. .doOnTerminate(() -> {
  36. log.debug("Terminating websocket client, disposing subscriptions");
  37. inboundSub.dispose();
  38. receiverSub.dispose();
  39. senderSub.dispose();
  40. })
  41. .then();
  42. });
  43. }
  44.  
  45. public Flux<I> inbound() {
  46. return receiver;
  47. }
  48.  
  49. public FluxSink<O> outbound() {
  50. return senderSink;
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment