-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketDemo.java
More file actions
123 lines (111 loc) · 4.13 KB
/
Copy pathWebSocketDemo.java
File metadata and controls
123 lines (111 loc) · 4.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package Phase8_PracticalAPIs.HttpClient;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
/**
* WebSocket API — java.net.http.WebSocket (Java 11+)
* --------------------------------------------------
* Full-duplex messaging. Built on the same HttpClient.
* <p>
*
* The two roles
* -------------
* WebSocket - the connection.
* WebSocket.Listener - callback interface for incoming events.
* <p>
*
* Listener methods
* ----------------
* onOpen(WebSocket)
* onText(WebSocket, CharSequence, boolean last)
* onBinary(WebSocket, ByteBuffer, boolean last)
* onPing(WebSocket, ByteBuffer)
* onPong(WebSocket, ByteBuffer)
* onClose(WebSocket, int statusCode, String reason)
* onError(WebSocket, Throwable)
* <p>
*
* Each callback returns a CompletionStage<?>; return null to mean
* "done, ready for more." The runtime requests one frame at a time
* via webSocket.request(n).
* <p>
*
* Building & sending
* ------------------
* HttpClient.newHttpClient()
* .newWebSocketBuilder()
* .buildAsync(uri, listener) -> CompletableFuture<WebSocket>
* <p>
*
* webSocket.sendText("hello", boolean last) -> CompletableFuture<WebSocket>
* webSocket.sendBinary(buf, boolean last)
* webSocket.sendPing / sendPong / sendClose
* <p>
*
* Common pitfalls
* ---------------
* - The listener returns a CompletionStage — if you forget, the
* runtime stops feeding messages.
* - Call webSocket.request(1) (or larger) inside onText to keep
* receiving — the default Listener defaults to 1 per callback.
* - sendClose must be matched on both sides.
* <p>
*
* Example endpoint
* ----------------
* For a quick check use wss://echo.websocket.events/ — it echoes
* whatever you send. Network required.
*/
public class WebSocketDemo {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
WebSocket.Listener listener = new EchoListener();
section("1) Connect");
CompletableFuture<WebSocket> connect = client
.newWebSocketBuilder()
.connectTimeout(Duration.ofSeconds(5))
.buildAsync(URI.create("wss://echo.websocket.events/"), listener);
WebSocket ws;
try {
ws = connect.get(8, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println("(network error - offline? " + e.getClass().getSimpleName() + ")");
return;
}
System.out.println("connected!");
section("2) Send 3 messages");
ws.sendText("hello", true).join();
ws.sendText("how are you?", true).join();
ws.sendText("goodbye", true).join();
section("3) Wait a moment for echoes");
Thread.sleep(1500);
section("4) Close cleanly");
ws.sendClose(WebSocket.NORMAL_CLOSURE, "bye").get(5, TimeUnit.SECONDS);
System.out.println("done");
}
static class EchoListener implements WebSocket.Listener {
@Override public void onOpen(WebSocket ws) {
System.out.println(" [listener] open");
ws.request(Long.MAX_VALUE); // request all subsequent frames
}
@Override public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
System.out.println(" [listener] <- " + data);
return null; // null = done with this message
}
@Override public CompletionStage<?> onClose(WebSocket ws, int statusCode, String reason) {
System.out.println(" [listener] closed " + statusCode + " " + reason);
return null;
}
@Override public void onError(WebSocket ws, Throwable error) {
System.out.println(" [listener] error " + error);
}
}
private static void section(String title) {
System.out.println();
System.out.println("=== " + title + " ===");
}
}