1 package org
.argeo
.cms
.client
;
3 import java
.math
.RoundingMode
;
5 import java
.net
.http
.HttpClient
;
6 import java
.net
.http
.WebSocket
;
7 import java
.nio
.ByteBuffer
;
8 import java
.text
.DecimalFormat
;
10 import java
.util
.concurrent
.CompletableFuture
;
11 import java
.util
.concurrent
.CompletionStage
;
12 import java
.util
.concurrent
.ExecutionException
;
14 /** Tests connectivity to the web socket server. */
15 public class WebSocketPing
implements Runnable
{
16 private final static int PING_FRAME_SIZE
= 125;
17 private final static DecimalFormat decimalFormat
= new DecimalFormat("0.0");
19 decimalFormat
.setRoundingMode(RoundingMode
.HALF_UP
);
22 private final URI uri
;
23 private final UUID uuid
;
25 private WebSocket webSocket
;
27 public WebSocketPing(URI uri
) {
29 this.uuid
= UUID
.randomUUID();
35 WebSocket
.Listener listener
= new WebSocket
.Listener() {
38 public CompletionStage
<?
> onPong(WebSocket webSocket
, ByteBuffer message
) {
39 long msb
= message
.getLong();
40 long lsb
= message
.getLong();
41 long end
= System
.nanoTime();
42 if (msb
!= uuid
.getMostSignificantBits() || lsb
!= uuid
.getLeastSignificantBits())
43 return null; // ignore
44 long begin
= message
.getLong();
45 double durationNs
= end
- begin
;
46 double durationMs
= durationNs
/ 1000000;
47 int size
= message
.remaining() + (3 * Long
.BYTES
);
49 size
+ " bytes from " + uri
+ ": time=" + decimalFormat
.format(durationMs
) + " ms");
55 HttpClient client
= HttpClient
.newHttpClient();
56 CompletableFuture
<WebSocket
> ws
= client
.newWebSocketBuilder().buildAsync(uri
, listener
);
58 webSocket
.request(Long
.MAX_VALUE
);
60 Runtime
.getRuntime().addShutdownHook(new Thread(() -> webSocket
.sendClose(WebSocket
.NORMAL_CLOSURE
, "")));
62 while (!webSocket
.isInputClosed()) {
63 long begin
= System
.nanoTime();
64 ByteBuffer buffer
= ByteBuffer
.allocate(PING_FRAME_SIZE
);
65 buffer
.putLong(uuid
.getMostSignificantBits());
66 buffer
.putLong(uuid
.getLeastSignificantBits());
67 buffer
.putLong(begin
);
69 webSocket
.sendPing(buffer
);
72 } catch (InterruptedException e
) {
73 if (webSocket
!= null)
74 webSocket
.sendClose(WebSocket
.NORMAL_CLOSURE
, "");
75 } catch (ExecutionException e
) {
76 throw new RuntimeException("Cannot ping " + uri
, e
.getCause());
80 // public static void main(String[] args) throws Exception {
81 // if (args.length == 0) {
82 // System.err.println("usage: java " + WsPing.class.getName() + " <url>");
86 // URI uri = URI.create(args[0]);
87 // new WsPing(uri).run();