]> git.argeo.org Git - lgpl/argeo-commons.git/blob - WsPing.java
55d6f047fbe0c47e5f4d9eb8deeefa79ffa4f2e9
[lgpl/argeo-commons.git] / WsPing.java
1 package org.argeo.cms.client;
2
3 import java.math.RoundingMode;
4 import java.net.URI;
5 import java.net.http.HttpClient;
6 import java.net.http.WebSocket;
7 import java.nio.ByteBuffer;
8 import java.text.DecimalFormat;
9 import java.util.UUID;
10 import java.util.concurrent.CompletableFuture;
11 import java.util.concurrent.CompletionStage;
12 import java.util.concurrent.ExecutionException;
13
14 /** Tests connectivity to the web socket server. */
15 public class WsPing implements Runnable {
16 private final static int PING_FRAME_SIZE = 125;
17
18 private final URI uri;
19 private final UUID uuid;
20
21 private final DecimalFormat decimalFormat;
22
23 public WsPing(URI uri) {
24 this.uri = uri;
25 this.uuid = UUID.randomUUID();
26 decimalFormat = new DecimalFormat("0.0");
27 decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
28 }
29
30 @Override
31 public void run() {
32 try {
33 WebSocket.Listener listener = new WebSocket.Listener() {
34
35 @Override
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);
46 System.out.println(
47 size + " bytes from " + uri + ": time=" + decimalFormat.format(durationMs) + " ms");
48 return null;
49 }
50
51 };
52
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);
57
58 Runtime.getRuntime().addShutdownHook(new Thread(() -> webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "")));
59
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);
66 buffer.flip();
67 webSocket.sendPing(buffer);
68 Thread.sleep(1000);
69 }
70 } catch (InterruptedException | ExecutionException e) {
71 e.printStackTrace();
72 }
73 }
74
75 public static void main(String[] args) throws Exception {
76 if (args.length == 0) {
77 System.err.println("usage: java " + WsPing.class.getName() + " <url>");
78 System.exit(1);
79 return;
80 }
81 URI uri = URI.create(args[0]);
82 new WsPing(uri).run();
83 }
84
85 }