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 WsPing
implements Runnable
{
16 private final static int PING_FRAME_SIZE
= 125;
18 private final URI uri
;
19 private final UUID uuid
;
21 private final DecimalFormat decimalFormat
;
23 public WsPing(URI uri
) {
25 this.uuid
= UUID
.randomUUID();
26 decimalFormat
= new DecimalFormat("0.0");
27 decimalFormat
.setRoundingMode(RoundingMode
.HALF_UP
);
33 WebSocket
.Listener listener
= new WebSocket
.Listener() {
36 public CompletionStage
<?
> onPong(WebSocket webSocket
, ByteBuffer message
) {
37 long msb
= message
.getLong();
38 long lsb
= message
.getLong();
39 long end
= System
.nanoTime();
40 if (msb
!= uuid
.getMostSignificantBits() || lsb
!= uuid
.getLeastSignificantBits())
41 return null; // ignore
42 long begin
= message
.getLong();
43 double durationNs
= end
- begin
;
44 double durationMs
= durationNs
/ 1000000;
45 int size
= message
.remaining() + (3 * Long
.BYTES
);
47 size
+ " bytes from " + uri
+ ": time=" + decimalFormat
.format(durationMs
) + " ms");
53 HttpClient client
= HttpClient
.newHttpClient();
54 CompletableFuture
<WebSocket
> ws
= client
.newWebSocketBuilder().buildAsync(uri
, listener
);
55 WebSocket webSocket
= ws
.get();
56 webSocket
.request(Long
.MAX_VALUE
);
58 Runtime
.getRuntime().addShutdownHook(new Thread(() -> webSocket
.sendClose(WebSocket
.NORMAL_CLOSURE
, "")));
60 while (!webSocket
.isInputClosed()) {
61 long begin
= System
.nanoTime();
62 ByteBuffer buffer
= ByteBuffer
.allocate(PING_FRAME_SIZE
);
63 buffer
.putLong(uuid
.getMostSignificantBits());
64 buffer
.putLong(uuid
.getLeastSignificantBits());
65 buffer
.putLong(begin
);
67 webSocket
.sendPing(buffer
);
70 } catch (InterruptedException
| ExecutionException e
) {
75 public static void main(String
[] args
) throws Exception
{
76 if (args
.length
== 0) {
77 System
.err
.println("usage: java " + WsPing
.class.getName() + " <url>");
81 URI uri
= URI
.create(args
[0]);
82 new WsPing(uri
).run();