37874
|
1 |
/*
|
|
2 |
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
|
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 |
*
|
|
5 |
* This code is free software; you can redistribute it and/or modify it
|
|
6 |
* under the terms of the GNU General Public License version 2 only, as
|
|
7 |
* published by the Free Software Foundation. Oracle designates this
|
|
8 |
* particular file as subject to the "Classpath" exception as provided
|
|
9 |
* by Oracle in the LICENSE file that accompanied this code.
|
|
10 |
*
|
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that
|
|
15 |
* accompanied this code).
|
|
16 |
*
|
|
17 |
* You should have received a copy of the GNU General Public License version
|
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
20 |
*
|
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
22 |
* or visit www.oracle.com if you need additional information or have any
|
|
23 |
* questions.
|
|
24 |
*/
|
|
25 |
package java.net.http;
|
|
26 |
|
|
27 |
import java.io.IOException;
|
|
28 |
import java.net.ProtocolException;
|
|
29 |
import java.net.http.WSOpeningHandshake.Result;
|
|
30 |
import java.nio.ByteBuffer;
|
|
31 |
import java.util.Optional;
|
|
32 |
import java.util.concurrent.CompletableFuture;
|
|
33 |
import java.util.concurrent.CompletionStage;
|
|
34 |
import java.util.concurrent.Executor;
|
|
35 |
import java.util.function.Consumer;
|
|
36 |
import java.util.function.Supplier;
|
|
37 |
import java.util.stream.Stream;
|
|
38 |
|
|
39 |
import static java.lang.System.Logger.Level.ERROR;
|
|
40 |
import static java.lang.System.Logger.Level.WARNING;
|
|
41 |
import static java.net.http.WSUtils.logger;
|
|
42 |
import static java.util.Objects.requireNonNull;
|
|
43 |
|
|
44 |
/*
|
|
45 |
* A WebSocket client.
|
|
46 |
*
|
|
47 |
* Consists of two independent parts; a transmitter responsible for sending
|
|
48 |
* messages, and a receiver which notifies the listener of incoming messages.
|
|
49 |
*/
|
|
50 |
final class WS implements WebSocket {
|
|
51 |
|
|
52 |
private final String subprotocol;
|
|
53 |
private final RawChannel channel;
|
|
54 |
private final WSTransmitter transmitter;
|
|
55 |
private final WSReceiver receiver;
|
|
56 |
private final Listener listener;
|
|
57 |
private final Object stateLock = new Object();
|
|
58 |
private volatile State state = State.CONNECTED;
|
|
59 |
private final CompletableFuture<Void> whenClosed = new CompletableFuture<>();
|
|
60 |
|
|
61 |
static CompletableFuture<WebSocket> newInstanceAsync(WSBuilder b) {
|
|
62 |
CompletableFuture<Result> result = new WSOpeningHandshake(b).performAsync();
|
|
63 |
Listener listener = b.getListener();
|
|
64 |
Executor executor = b.getClient().executorService();
|
|
65 |
return result.thenApply(r -> {
|
|
66 |
WS ws = new WS(listener, r.subprotocol, r.channel, executor);
|
|
67 |
ws.start();
|
|
68 |
return ws;
|
|
69 |
});
|
|
70 |
}
|
|
71 |
|
|
72 |
private WS(Listener listener, String subprotocol, RawChannel channel,
|
|
73 |
Executor executor) {
|
|
74 |
this.listener = wrapListener(listener);
|
|
75 |
this.channel = channel;
|
|
76 |
this.subprotocol = subprotocol;
|
|
77 |
Consumer<Throwable> errorHandler = error -> {
|
|
78 |
if (error == null) {
|
|
79 |
throw new InternalError();
|
|
80 |
}
|
|
81 |
// If the channel is closed, we need to update the state, to denote
|
|
82 |
// there's no point in trying to continue using WebSocket
|
|
83 |
if (!channel.isOpen()) {
|
|
84 |
synchronized (stateLock) {
|
|
85 |
tryChangeState(State.ERROR);
|
|
86 |
}
|
|
87 |
}
|
|
88 |
};
|
|
89 |
transmitter = new WSTransmitter(executor, channel, errorHandler);
|
|
90 |
receiver = new WSReceiver(this.listener, this, executor, channel);
|
|
91 |
}
|
|
92 |
|
|
93 |
private void start() {
|
|
94 |
receiver.start();
|
|
95 |
}
|
|
96 |
|
|
97 |
@Override
|
|
98 |
public CompletableFuture<Void> sendText(ByteBuffer message, boolean isLast) {
|
|
99 |
throw new UnsupportedOperationException("Not implemented");
|
|
100 |
}
|
|
101 |
|
|
102 |
@Override
|
|
103 |
public CompletableFuture<Void> sendText(CharSequence message, boolean isLast) {
|
|
104 |
requireNonNull(message, "message");
|
|
105 |
synchronized (stateLock) {
|
|
106 |
checkState();
|
|
107 |
return transmitter.sendText(message, isLast);
|
|
108 |
}
|
|
109 |
}
|
|
110 |
|
|
111 |
@Override
|
|
112 |
public CompletableFuture<Void> sendText(Stream<? extends CharSequence> message) {
|
|
113 |
requireNonNull(message, "message");
|
|
114 |
synchronized (stateLock) {
|
|
115 |
checkState();
|
|
116 |
return transmitter.sendText(message);
|
|
117 |
}
|
|
118 |
}
|
|
119 |
|
|
120 |
@Override
|
|
121 |
public CompletableFuture<Void> sendBinary(ByteBuffer message, boolean isLast) {
|
|
122 |
requireNonNull(message, "message");
|
|
123 |
synchronized (stateLock) {
|
|
124 |
checkState();
|
|
125 |
return transmitter.sendBinary(message, isLast);
|
|
126 |
}
|
|
127 |
}
|
|
128 |
|
|
129 |
@Override
|
|
130 |
public CompletableFuture<Void> sendPing(ByteBuffer message) {
|
|
131 |
requireNonNull(message, "message");
|
|
132 |
synchronized (stateLock) {
|
|
133 |
checkState();
|
|
134 |
return transmitter.sendPing(message);
|
|
135 |
}
|
|
136 |
}
|
|
137 |
|
|
138 |
@Override
|
|
139 |
public CompletableFuture<Void> sendPong(ByteBuffer message) {
|
|
140 |
requireNonNull(message, "message");
|
|
141 |
synchronized (stateLock) {
|
|
142 |
checkState();
|
|
143 |
return transmitter.sendPong(message);
|
|
144 |
}
|
|
145 |
}
|
|
146 |
|
|
147 |
@Override
|
|
148 |
public CompletableFuture<Void> sendClose(CloseCode code, CharSequence reason) {
|
|
149 |
requireNonNull(code, "code");
|
|
150 |
requireNonNull(reason, "reason");
|
|
151 |
synchronized (stateLock) {
|
|
152 |
return doSendClose(() -> transmitter.sendClose(code, reason));
|
|
153 |
}
|
|
154 |
}
|
|
155 |
|
|
156 |
@Override
|
|
157 |
public CompletableFuture<Void> sendClose() {
|
|
158 |
synchronized (stateLock) {
|
|
159 |
return doSendClose(() -> transmitter.sendClose());
|
|
160 |
}
|
|
161 |
}
|
|
162 |
|
|
163 |
private CompletableFuture<Void> doSendClose(Supplier<CompletableFuture<Void>> s) {
|
|
164 |
checkState();
|
|
165 |
boolean closeChannel = false;
|
|
166 |
synchronized (stateLock) {
|
|
167 |
if (state == State.CLOSED_REMOTELY) {
|
|
168 |
closeChannel = tryChangeState(State.CLOSED);
|
|
169 |
} else {
|
|
170 |
tryChangeState(State.CLOSED_LOCALLY);
|
|
171 |
}
|
|
172 |
}
|
|
173 |
CompletableFuture<Void> sent = s.get();
|
|
174 |
if (closeChannel) {
|
|
175 |
sent.whenComplete((v, t) -> {
|
|
176 |
try {
|
|
177 |
channel.close();
|
|
178 |
} catch (IOException e) {
|
|
179 |
logger.log(ERROR, "Error transitioning to state " + State.CLOSED, e);
|
|
180 |
}
|
|
181 |
});
|
|
182 |
}
|
|
183 |
return sent;
|
|
184 |
}
|
|
185 |
|
|
186 |
@Override
|
|
187 |
public long request(long n) {
|
|
188 |
if (n < 0L) {
|
|
189 |
throw new IllegalArgumentException("The number must not be negative: " + n);
|
|
190 |
}
|
|
191 |
return receiver.request(n);
|
|
192 |
}
|
|
193 |
|
|
194 |
@Override
|
|
195 |
public String getSubprotocol() {
|
|
196 |
return subprotocol;
|
|
197 |
}
|
|
198 |
|
|
199 |
@Override
|
|
200 |
public boolean isClosed() {
|
|
201 |
return state.isTerminal();
|
|
202 |
}
|
|
203 |
|
|
204 |
@Override
|
|
205 |
public void abort() throws IOException {
|
|
206 |
synchronized (stateLock) {
|
|
207 |
tryChangeState(State.ABORTED);
|
|
208 |
}
|
|
209 |
channel.close();
|
|
210 |
}
|
|
211 |
|
|
212 |
@Override
|
|
213 |
public String toString() {
|
|
214 |
return super.toString() + "[" + state + "]";
|
|
215 |
}
|
|
216 |
|
|
217 |
private void checkState() {
|
|
218 |
if (state.isTerminal() || state == State.CLOSED_LOCALLY) {
|
|
219 |
throw new IllegalStateException("WebSocket is closed [" + state + "]");
|
|
220 |
}
|
|
221 |
}
|
|
222 |
|
|
223 |
/*
|
|
224 |
* Wraps the user's listener passed to the constructor into own listener to
|
|
225 |
* intercept transitions to terminal states (onClose and onError) and to act
|
|
226 |
* upon exceptions and values from the user's listener.
|
|
227 |
*/
|
|
228 |
private Listener wrapListener(Listener listener) {
|
|
229 |
return new Listener() {
|
|
230 |
|
|
231 |
// Listener's method MUST be invoked in a happen-before order
|
|
232 |
private final Object visibilityLock = new Object();
|
|
233 |
|
|
234 |
@Override
|
|
235 |
public void onOpen(WebSocket webSocket) {
|
|
236 |
synchronized (visibilityLock) {
|
|
237 |
listener.onOpen(webSocket);
|
|
238 |
}
|
|
239 |
}
|
|
240 |
|
|
241 |
@Override
|
|
242 |
public CompletionStage<?> onText(WebSocket webSocket, Text message,
|
|
243 |
MessagePart part) {
|
|
244 |
synchronized (visibilityLock) {
|
|
245 |
return listener.onText(webSocket, message, part);
|
|
246 |
}
|
|
247 |
}
|
|
248 |
|
|
249 |
@Override
|
|
250 |
public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer message,
|
|
251 |
MessagePart part) {
|
|
252 |
synchronized (visibilityLock) {
|
|
253 |
return listener.onBinary(webSocket, message, part);
|
|
254 |
}
|
|
255 |
}
|
|
256 |
|
|
257 |
@Override
|
|
258 |
public CompletionStage<?> onPing(WebSocket webSocket, ByteBuffer message) {
|
|
259 |
synchronized (visibilityLock) {
|
|
260 |
return listener.onPing(webSocket, message);
|
|
261 |
}
|
|
262 |
}
|
|
263 |
|
|
264 |
@Override
|
|
265 |
public CompletionStage<?> onPong(WebSocket webSocket, ByteBuffer message) {
|
|
266 |
synchronized (visibilityLock) {
|
|
267 |
return listener.onPong(webSocket, message);
|
|
268 |
}
|
|
269 |
}
|
|
270 |
|
|
271 |
@Override
|
|
272 |
public void onClose(WebSocket webSocket, Optional<CloseCode> code, String reason) {
|
|
273 |
synchronized (stateLock) {
|
|
274 |
if (state == State.CLOSED_REMOTELY || state.isTerminal()) {
|
|
275 |
throw new InternalError("Unexpected onClose in state " + state);
|
|
276 |
} else if (state == State.CLOSED_LOCALLY) {
|
|
277 |
try {
|
|
278 |
channel.close();
|
|
279 |
} catch (IOException e) {
|
|
280 |
logger.log(ERROR, "Error transitioning to state " + State.CLOSED, e);
|
|
281 |
}
|
|
282 |
tryChangeState(State.CLOSED);
|
|
283 |
} else if (state == State.CONNECTED) {
|
|
284 |
tryChangeState(State.CLOSED_REMOTELY);
|
|
285 |
}
|
|
286 |
}
|
|
287 |
synchronized (visibilityLock) {
|
|
288 |
listener.onClose(webSocket, code, reason);
|
|
289 |
}
|
|
290 |
}
|
|
291 |
|
|
292 |
@Override
|
|
293 |
public void onError(WebSocket webSocket, Throwable error) {
|
|
294 |
// An error doesn't necessarily mean the connection must be
|
|
295 |
// closed automatically
|
|
296 |
if (!channel.isOpen()) {
|
|
297 |
synchronized (stateLock) {
|
|
298 |
tryChangeState(State.ERROR);
|
|
299 |
}
|
|
300 |
} else if (error instanceof ProtocolException
|
|
301 |
&& error.getCause() instanceof WSProtocolException) {
|
|
302 |
WSProtocolException cause = (WSProtocolException) error.getCause();
|
|
303 |
logger.log(WARNING, "Failing connection {0}, reason: ''{1}''",
|
|
304 |
webSocket, cause.getMessage());
|
|
305 |
CloseCode cc = cause.getCloseCode();
|
|
306 |
transmitter.sendClose(cc, "").whenComplete((v, t) -> {
|
|
307 |
synchronized (stateLock) {
|
|
308 |
tryChangeState(State.ERROR);
|
|
309 |
}
|
|
310 |
try {
|
|
311 |
channel.close();
|
|
312 |
} catch (IOException e) {
|
|
313 |
logger.log(ERROR, e);
|
|
314 |
}
|
|
315 |
});
|
|
316 |
}
|
|
317 |
synchronized (visibilityLock) {
|
|
318 |
listener.onError(webSocket, error);
|
|
319 |
}
|
|
320 |
}
|
|
321 |
};
|
|
322 |
}
|
|
323 |
|
|
324 |
private boolean tryChangeState(State newState) {
|
|
325 |
assert Thread.holdsLock(stateLock);
|
|
326 |
if (state.isTerminal()) {
|
|
327 |
return false;
|
|
328 |
}
|
|
329 |
state = newState;
|
|
330 |
if (newState.isTerminal()) {
|
|
331 |
whenClosed.complete(null);
|
|
332 |
}
|
|
333 |
return true;
|
|
334 |
}
|
|
335 |
|
|
336 |
CompletionStage<Void> whenClosed() {
|
|
337 |
return whenClosed;
|
|
338 |
}
|
|
339 |
|
|
340 |
/*
|
|
341 |
* WebSocket connection internal state.
|
|
342 |
*/
|
|
343 |
private enum State {
|
|
344 |
|
|
345 |
/*
|
|
346 |
* Initial WebSocket state. The WebSocket is connected (i.e. remains in
|
|
347 |
* this state) unless proven otherwise. For example, by reading or
|
|
348 |
* writing operations on the channel.
|
|
349 |
*/
|
|
350 |
CONNECTED,
|
|
351 |
|
|
352 |
/*
|
|
353 |
* A Close message has been received by the client. No more messages
|
|
354 |
* will be received.
|
|
355 |
*/
|
|
356 |
CLOSED_REMOTELY,
|
|
357 |
|
|
358 |
/*
|
|
359 |
* A Close message has been sent by the client. No more messages can be
|
|
360 |
* sent.
|
|
361 |
*/
|
|
362 |
CLOSED_LOCALLY,
|
|
363 |
|
|
364 |
/*
|
|
365 |
* Close messages has been both sent and received (closing handshake)
|
|
366 |
* and TCP connection closed. Closed _cleanly_ in terms of RFC 6455.
|
|
367 |
*/
|
|
368 |
CLOSED,
|
|
369 |
|
|
370 |
/*
|
|
371 |
* The connection has been aborted by the client. Closed not _cleanly_
|
|
372 |
* in terms of RFC 6455.
|
|
373 |
*/
|
|
374 |
ABORTED,
|
|
375 |
|
|
376 |
/*
|
|
377 |
* The connection has been terminated due to a protocol or I/O error.
|
|
378 |
* Might happen during sending or receiving.
|
|
379 |
*/
|
|
380 |
ERROR;
|
|
381 |
|
|
382 |
/*
|
|
383 |
* Returns `true` if this state is terminal. If WebSocket has transited
|
|
384 |
* to such a state, if remains in it forever.
|
|
385 |
*/
|
|
386 |
boolean isTerminal() {
|
|
387 |
return this == CLOSED || this == ABORTED || this == ERROR;
|
|
388 |
}
|
|
389 |
}
|
|
390 |
}
|