Send a message over the WebSocket. Accepts String or Object (serialized to JSON). Returns a CompletableFuture that completes when the message is flushed to the network. Callers should handle the returned future to detect send failures.
(Object message)
| 554 | * Callers should handle the returned future to detect send failures. |
| 555 | */ |
| 556 | public CompletableFuture<Void> send(Object message) { |
| 557 | String json; |
| 558 | if (message instanceof String s) { |
| 559 | json = s; |
| 560 | } else { |
| 561 | try { |
| 562 | json = JSON_MAPPER.writeValueAsString(message); |
| 563 | } catch (Exception e) { |
| 564 | json = String.valueOf(message); |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | if (this.verbose) { |
| 569 | System.out.println(getFormattedDate() + "Sending: " + json); |
| 570 | } |
| 571 | |
| 572 | if (this.channel != null && this.channel.isActive()) { |
| 573 | CompletableFuture<Void> result = new CompletableFuture<>(); |
| 574 | this.channel.writeAndFlush(new TextWebSocketFrame(json)).addListener(future -> { |
| 575 | if (future.isSuccess()) { |
| 576 | result.complete(null); |
| 577 | } else { |
| 578 | result.completeExceptionally(future.cause()); |
| 579 | } |
| 580 | }); |
| 581 | return result; |
| 582 | } |
| 583 | return CompletableFuture.failedFuture( |
| 584 | new RuntimeException("WebSocket not connected: " + this.url)); |
| 585 | } |
| 586 | |
| 587 | /** |
| 588 | * Close the WebSocket connection and reject all pending futures. |