-
Notifications
You must be signed in to change notification settings - Fork 291
/
ReadingThread.java
1204 lines (974 loc) · 33.8 KB
/
ReadingThread.java
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015-2017 Neo Visionaries Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.neovisionaries.ws.client;
import static com.neovisionaries.ws.client.WebSocketOpcode.BINARY;
import static com.neovisionaries.ws.client.WebSocketOpcode.CLOSE;
import static com.neovisionaries.ws.client.WebSocketOpcode.CONTINUATION;
import static com.neovisionaries.ws.client.WebSocketOpcode.PING;
import static com.neovisionaries.ws.client.WebSocketOpcode.PONG;
import static com.neovisionaries.ws.client.WebSocketOpcode.TEXT;
import static com.neovisionaries.ws.client.WebSocketState.CLOSED;
import static com.neovisionaries.ws.client.WebSocketState.CLOSING;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.neovisionaries.ws.client.StateManager.CloseInitiator;
class ReadingThread extends WebSocketThread
{
private boolean mStopRequested;
private WebSocketFrame mCloseFrame;
private List<WebSocketFrame> mContinuation = new ArrayList<WebSocketFrame>();
private final PerMessageCompressionExtension mPMCE;
private Object mCloseLock = new Object();
private Timer mCloseTimer;
private CloseTask mCloseTask;
private long mCloseDelay;
private boolean mNotWaitForCloseFrame;
public ReadingThread(WebSocket websocket)
{
super("ReadingThread", websocket, ThreadType.READING_THREAD);
mPMCE = websocket.getPerMessageCompressionExtension();
}
@Override
public void runMain()
{
try
{
main();
}
catch (Throwable t)
{
// An uncaught throwable was detected in the reading thread.
WebSocketException cause = new WebSocketException(
WebSocketError.UNEXPECTED_ERROR_IN_READING_THREAD,
"An uncaught throwable was detected in the reading thread: " + t.getMessage(), t);
// Notify the listeners.
ListenerManager manager = mWebSocket.getListenerManager();
manager.callOnError(cause);
manager.callOnUnexpectedError(cause);
}
// Notify this reading thread finished.
notifyFinished();
}
private void main()
{
mWebSocket.onReadingThreadStarted();
while (true)
{
synchronized (this)
{
if (mStopRequested)
{
break;
}
}
// Receive a frame from the server.
WebSocketFrame frame = readFrame();
if (frame == null)
{
// Something unexpected happened.
break;
}
// Handle the frame.
boolean keepReading = handleFrame(frame);
if (keepReading == false)
{
break;
}
}
// Wait for a close frame if one has not been received yet.
waitForCloseFrame();
// Cancel a task which calls Socket.close() if running.
cancelClose();
}
void requestStop(long closeDelay)
{
synchronized (this)
{
if (mStopRequested)
{
return;
}
mStopRequested = true;
}
// interrupt() may not interrupt a blocking socket read(), so calling
// interrupt() here may not work. interrupt() in Java is different
// from signal-based interruption in C which unblocks a read() system
// call. Anyway, let's mark this thread as interrupted.
interrupt();
// To surely unblock a read() call, Socket.close() needs to be called.
// Or, shutdownInterrupt() may work, but it is not explicitly stated
// in the JavaDoc. In either case, interruption should not be executed
// now because a close frame from the server should be waited for.
//
// So, let's schedule a task with some delay which calls Socket.close().
// However, in normal cases, a close frame will arrive from the server
// before the task calls Socket.close().
mCloseDelay = closeDelay;
scheduleClose();
}
/**
* Call {@link WebSocketListener#onFrame(WebSocket, WebSocketFrame) onFrame}
* method of the listeners.
*/
private void callOnFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnFrame(frame);
}
/**
* Call {@link WebSocketListener#onContinuationFrame(WebSocket, WebSocketFrame)
* onContinuationFrame} method of the listeners.
*/
private void callOnContinuationFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnContinuationFrame(frame);
}
/**
* Call {@link WebSocketListener#onTextFrame(WebSocket, WebSocketFrame)
* onTextFrame} method of the listeners.
*/
private void callOnTextFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnTextFrame(frame);
}
/**
* Call {@link WebSocketListener#onBinaryFrame(WebSocket, WebSocketFrame)
* onBinaryFrame} method of the listeners.
*/
private void callOnBinaryFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnBinaryFrame(frame);
}
/**
* Call {@link WebSocketListener#onCloseFrame(WebSocket, WebSocketFrame)
* onCloseFrame} method of the listeners.
*/
private void callOnCloseFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnCloseFrame(frame);
}
/**
* Call {@link WebSocketListener#onPingFrame(WebSocket, WebSocketFrame)
* onPingFrame} method of the listeners.
*/
private void callOnPingFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnPingFrame(frame);
}
/**
* Call {@link WebSocketListener#onPongFrame(WebSocket, WebSocketFrame)
* onPongFrame} method of the listeners.
*/
private void callOnPongFrame(WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnPongFrame(frame);
}
/**
* Call {@link WebSocketListener#onTextMessage(WebSocket, String)
* onTextMessage} method of the listeners.
*/
private void callOnTextMessage(byte[] data)
{
if (mWebSocket.isDirectTextMessage())
{
mWebSocket.getListenerManager().callOnTextMessage(data);
return;
}
try
{
// Interpret the byte array as a string.
// OutOfMemoryError may happen when the size of data is too big.
String message = Misc.toStringUTF8(data);
// Call onTextMessage() method of the listeners.
callOnTextMessage(message);
}
catch (Throwable t)
{
// Failed to convert payload data into a string.
WebSocketException wse = new WebSocketException(
WebSocketError.TEXT_MESSAGE_CONSTRUCTION_ERROR,
"Failed to convert payload data into a string: " + t.getMessage(), t);
// Notify the listeners that text message construction failed.
callOnError(wse);
callOnTextMessageError(wse, data);
}
}
/**
* Call {@link WebSocketListener#onTextMessage(WebSocket, String)
* onTextMessage} method of the listeners.
*/
private void callOnTextMessage(String message)
{
mWebSocket.getListenerManager().callOnTextMessage(message);
}
/**
* Call {@link WebSocketListener#onBinaryMessage(WebSocket, String)
* onBinaryMessage} method of the listeners.
*/
private void callOnBinaryMessage(byte[] message)
{
mWebSocket.getListenerManager().callOnBinaryMessage(message);
}
/**
* Call {@link WebSocketListener#onError(WebSocket, WebSocketException)
* onError} method of the listeners.
*/
private void callOnError(WebSocketException cause)
{
mWebSocket.getListenerManager().callOnError(cause);
}
/**
* Call {@link WebSocketListener#onFrameError(WebSocket,
* WebSocketException, WebSocketFrame) onFrameError} method of the listeners.
*/
private void callOnFrameError(WebSocketException cause, WebSocketFrame frame)
{
mWebSocket.getListenerManager().callOnFrameError(cause, frame);
}
/**
* Call {@link WebSocketListener#onMessageError(WebSocket, WebSocketException, List)
* onMessageError} method of the listeners.
*/
private void callOnMessageError(WebSocketException cause, List<WebSocketFrame> frames)
{
mWebSocket.getListenerManager().callOnMessageError(cause, frames);
}
/**
* Call {@link WebSocketListener#onMessageDecompressionError(WebSocket, WebSocketException, byte[])
* onMessageDecompressionError} method of the listeners.
*/
private void callOnMessageDecompressionError(WebSocketException cause, byte[] compressed)
{
mWebSocket.getListenerManager().callOnMessageDecompressionError(cause, compressed);
}
/**
* Call {@link WebSocketListener#onTextMessageError(WebSocket, WebSocketException, byte[])
* onTextMessageError} method of the listeners.
*/
private void callOnTextMessageError(WebSocketException cause, byte[] data)
{
mWebSocket.getListenerManager().callOnTextMessageError(cause, data);
}
private WebSocketFrame readFrame()
{
WebSocketFrame frame = null;
WebSocketException wse = null;
try
{
// Receive a frame from the server.
frame = mWebSocket.getInput().readFrame();
// Verify the frame. If invalid, WebSocketException is thrown.
verifyFrame(frame);
// Return the verified frame.
return frame;
}
catch (InterruptedIOException e)
{
if (mStopRequested)
{
// Thread.interrupt() interrupted a blocking socket read operation.
// This thread has been interrupted intentionally.
return null;
}
else
{
// Interruption occurred while a frame was being read from the web socket.
wse = new WebSocketException(
WebSocketError.INTERRUPTED_IN_READING,
"Interruption occurred while a frame was being read from the web socket: " + e.getMessage(), e);
}
}
catch (IOException e)
{
if (mStopRequested && isInterrupted())
{
// Socket.close() interrupted a blocking socket read operation.
// This thread has been interrupted intentionally.
return null;
}
else
{
// An I/O error occurred while a frame was being read from the web socket.
wse = new WebSocketException(
WebSocketError.IO_ERROR_IN_READING,
"An I/O error occurred while a frame was being read from the web socket: " + e.getMessage(), e);
}
}
catch (WebSocketException e)
{
// A protocol error.
wse = e;
}
boolean error = true;
// If the input stream of the WebSocket connection has reached the end
// without receiving a close frame from the server.
if (wse instanceof NoMoreFrameException)
{
// Not wait for a close frame in waitForCloseFrame() which will be called later.
mNotWaitForCloseFrame = true;
// If the configuration of the WebSocket instance allows the behavior.
if (mWebSocket.isMissingCloseFrameAllowed())
{
error = false;
}
}
if (error)
{
// Notify the listeners that an error occurred while a frame was being read.
callOnError(wse);
callOnFrameError(wse, frame);
}
// Create a close frame.
WebSocketFrame closeFrame = createCloseFrame(wse);
// Send the close frame.
mWebSocket.sendFrame(closeFrame);
// No WebSocket frame is available.
return null;
}
private void verifyFrame(WebSocketFrame frame) throws WebSocketException
{
// Verify RSV1, RSV2 and RSV3.
verifyReservedBits(frame);
// The opcode of the frame must be known.
verifyFrameOpcode(frame);
// Frames from the server must not be masked.
verifyFrameMask(frame);
// Verify fragmentation conditions.
verifyFrameFragmentation(frame);
// Verify the size of the payload.
verifyFrameSize(frame);
}
private void verifyReservedBits(WebSocketFrame frame) throws WebSocketException
{
// If extended use of web socket frames is allowed.
if (mWebSocket.isExtended())
{
// Do not check RSV1/RSV2/RSV3 bits.
return;
}
// RSV1, RSV2, RSV3
//
// The specification requires that these bits "be 0 unless an extension
// is negotiated that defines meanings for non-zero values".
verifyReservedBit1(frame);
verifyReservedBit2(frame);
verifyReservedBit3(frame);
}
/**
* Verify the RSV1 bit of a frame.
*/
private void verifyReservedBit1(WebSocketFrame frame) throws WebSocketException
{
// If a per-message compression extension has been agreed.
if (mPMCE != null)
{
// Verify the RSV1 bit using the rule described in RFC 7692.
boolean verified = verifyReservedBit1ForPMCE(frame);
if (verified)
{
return;
}
}
if (frame.getRsv1() == false)
{
// No problem.
return;
}
// The RSV1 bit of a frame is set unexpectedly.
throw new WebSocketException(
WebSocketError.UNEXPECTED_RESERVED_BIT, "The RSV1 bit of a frame is set unexpectedly.");
}
/**
* Verify the RSV1 bit of a frame using the rule described in RFC 7692.
* See <a href="https://tools.ietf.org/html/rfc7692#section-6">6. Framing</a>
* in <a href="https://tools.ietf.org/html/rfc7692">RFC 7692</a> for details.
*/
private boolean verifyReservedBit1ForPMCE(WebSocketFrame frame) throws WebSocketException
{
if (frame.isTextFrame() || frame.isBinaryFrame())
{
// The RSV1 of the first frame of a message is called
// "Per-Message Compressed" bit. It can be either 0 or 1.
// In other words, any value is okay.
return true;
}
// Further checking is required.
return false;
}
/**
* Verify the RSV2 bit of a frame.
*/
private void verifyReservedBit2(WebSocketFrame frame) throws WebSocketException
{
if (frame.getRsv2() == false)
{
// No problem.
return;
}
// The RSV2 bit of a frame is set unexpectedly.
throw new WebSocketException(
WebSocketError.UNEXPECTED_RESERVED_BIT, "The RSV2 bit of a frame is set unexpectedly.");
}
/**
* Verify the RSV3 bit of a frame.
*/
private void verifyReservedBit3(WebSocketFrame frame) throws WebSocketException
{
if (frame.getRsv3() == false)
{
// No problem.
return;
}
// The RSV3 bit of a frame is set unexpectedly.
throw new WebSocketException(
WebSocketError.UNEXPECTED_RESERVED_BIT, "The RSV3 bit of a frame is set unexpectedly.");
}
/**
* Ensure that the opcode of the give frame is a known one.
*
* <blockquote>
* <p>From RFC 6455, 5.2. Base Framing Protocol</p>
* <p><i>
* If an unknown opcode is received, the receiving endpoint MUST
* Fail the WebSocket Connection.
* </i></p>
* </blockquote>
*/
private void verifyFrameOpcode(WebSocketFrame frame) throws WebSocketException
{
switch (frame.getOpcode())
{
case CONTINUATION:
case TEXT:
case BINARY:
case CLOSE:
case PING:
case PONG:
// Known opcode
return;
default:
break;
}
// If extended use of web socket frames is allowed.
if (mWebSocket.isExtended())
{
// Allow the unknown opcode.
return;
}
// A frame has an unknown opcode.
throw new WebSocketException(
WebSocketError.UNKNOWN_OPCODE,
"A frame has an unknown opcode: 0x" + Integer.toHexString(frame.getOpcode()));
}
/**
* Ensure that the given frame is not masked.
*
* <blockquote>
* <p>From RFC 6455, 5.1. Overview:</p>
* <p><i>
* A server MUST NOT mask any frames that it sends to the client.
* A client MUST close a connection if it detects a masked frame.
* </i></p>
* </blockquote>
*/
private void verifyFrameMask(WebSocketFrame frame) throws WebSocketException
{
// If the frame is masked.
if (frame.getMask())
{
// A frame from the server is masked.
throw new WebSocketException(
WebSocketError.FRAME_MASKED,
"A frame from the server is masked.");
}
}
private void verifyFrameFragmentation(WebSocketFrame frame) throws WebSocketException
{
// Control frames (see Section 5.5) MAY be injected in the
// middle of a fragmented message. Control frames themselves
// MUST NOT be fragmented.
if (frame.isControlFrame())
{
// If fragmented.
if (frame.getFin() == false)
{
// A control frame is fragmented.
throw new WebSocketException(
WebSocketError.FRAGMENTED_CONTROL_FRAME,
"A control frame is fragmented.");
}
// No more requirements on a control frame.
return;
}
// True if a continuation has already started.
boolean continuationExists = (mContinuation.size() != 0);
// If the frame is a continuation frame.
if (frame.isContinuationFrame())
{
// There must already exist a continuation sequence.
if (continuationExists == false)
{
// A continuation frame was detected although a continuation had not started.
throw new WebSocketException(
WebSocketError.UNEXPECTED_CONTINUATION_FRAME,
"A continuation frame was detected although a continuation had not started.");
}
// No more requirements on a continuation frame.
return;
}
// A data frame.
if (continuationExists)
{
// A non-control frame was detected although the existing continuation had not been closed.
throw new WebSocketException(
WebSocketError.CONTINUATION_NOT_CLOSED,
"A non-control frame was detected although the existing continuation had not been closed.");
}
}
private void verifyFrameSize(WebSocketFrame frame) throws WebSocketException
{
// If the frame is not a control frame.
if (frame.isControlFrame() == false)
{
// Nothing to check.
return;
}
// RFC 6455, 5.5. Control Frames.
//
// All control frames MUST have a payload length of 125 bytes or less
// and MUST NOT be fragmented.
//
byte[] payload = frame.getPayload();
if (payload == null)
{
// The frame does not have payload.
return;
}
if (125 < payload.length)
{
// The payload size of a control frame exceeds the maximum size (125 bytes).
throw new WebSocketException(
WebSocketError.TOO_LONG_CONTROL_FRAME_PAYLOAD,
"The payload size of a control frame exceeds the maximum size (125 bytes): " + payload.length);
}
}
private WebSocketFrame createCloseFrame(WebSocketException wse)
{
int closeCode;
switch (wse.getError())
{
// In WebSocketInputStream.readFrame()
case INSUFFICENT_DATA:
case INVALID_PAYLOAD_LENGTH:
case NO_MORE_FRAME:
closeCode = WebSocketCloseCode.UNCONFORMED;
break;
case TOO_LONG_PAYLOAD:
case INSUFFICIENT_MEMORY_FOR_PAYLOAD:
closeCode = WebSocketCloseCode.OVERSIZE;
break;
// In this.verifyFrame(WebSocketFrame)
case NON_ZERO_RESERVED_BITS:
case UNEXPECTED_RESERVED_BIT:
case UNKNOWN_OPCODE:
case FRAME_MASKED:
case FRAGMENTED_CONTROL_FRAME:
case UNEXPECTED_CONTINUATION_FRAME:
case CONTINUATION_NOT_CLOSED:
case TOO_LONG_CONTROL_FRAME_PAYLOAD:
closeCode = WebSocketCloseCode.UNCONFORMED;
break;
// In this.readFrame()
case INTERRUPTED_IN_READING:
case IO_ERROR_IN_READING:
closeCode = WebSocketCloseCode.VIOLATED;
break;
// Others (unexpected)
default:
closeCode = WebSocketCloseCode.VIOLATED;
break;
}
return WebSocketFrame.createCloseFrame(closeCode, wse.getMessage());
}
private boolean handleFrame(WebSocketFrame frame)
{
// Notify the listeners that a frame was received.
callOnFrame(frame);
// Dispatch based on the opcode.
switch (frame.getOpcode())
{
case CONTINUATION:
return handleContinuationFrame(frame);
case TEXT:
return handleTextFrame(frame);
case BINARY:
return handleBinaryFrame(frame);
case CLOSE:
return handleCloseFrame(frame);
case PING:
return handlePingFrame(frame);
case PONG:
return handlePongFrame(frame);
default:
// Ignore the frame whose opcode is unknown. Keep reading.
return true;
}
}
private boolean handleContinuationFrame(WebSocketFrame frame)
{
// Notify the listeners that a continuation frame was received.
callOnContinuationFrame(frame);
// Append the continuation frame to the existing continuation sequence.
mContinuation.add(frame);
// If the frame is not the last one for the continuation.
if (frame.getFin() == false)
{
// Keep reading.
return true;
}
// Concatenate payloads of the frames. Decompression is performed
// when necessary.
byte[] data = getMessage(mContinuation);
// If the concatenation failed.
if (data == null)
{
// Stop reading.
return false;
}
// If the continuation forms a text message.
if (mContinuation.get(0).isTextFrame())
{
// Notify the listeners that a text message was received.
callOnTextMessage(data);
}
else
{
// Notify the listeners that a binary message was received.
callOnBinaryMessage(data);
}
// Clear the continuation.
mContinuation.clear();
// Keep reading.
return true;
}
private byte[] getMessage(List<WebSocketFrame> frames)
{
// Concatenate payloads of the frames.
byte[] data = concatenatePayloads(mContinuation);
// If the concatenation failed.
if (data == null)
{
// Stop reading.
return null;
}
// If a per-message compression extension is enabled and
// the Per-Message Compressed bit of the first frame is set.
if (mPMCE != null && frames.get(0).getRsv1())
{
// Decompress the data.
data = decompress(data);
}
return data;
}
private byte[] concatenatePayloads(List<WebSocketFrame> frames)
{
Throwable cause;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// For each web socket frame.
for (WebSocketFrame frame : frames)
{
// Get the payload of the frame.
byte[] payload = frame.getPayload();
// If the payload is null or empty.
if (payload == null || payload.length == 0)
{
continue;
}
// Append the payload.
baos.write(payload);
}
// Return the concatenated byte array.
return baos.toByteArray();
}
catch (IOException e)
{
cause = e;
}
catch (OutOfMemoryError e)
{
cause = e;
}
// Create a WebSocketException which has a cause.
WebSocketException wse = new WebSocketException(
WebSocketError.MESSAGE_CONSTRUCTION_ERROR,
"Failed to concatenate payloads of multiple frames to construct a message: " + cause.getMessage(), cause);
// Notify the listeners that message construction failed.
callOnError(wse);
callOnMessageError(wse, frames);
// Create a close frame with a close code of 1009 which
// indicates that the message is too big to process.
WebSocketFrame frame = WebSocketFrame
.createCloseFrame(WebSocketCloseCode.OVERSIZE, wse.getMessage());
// Send the close frame.
mWebSocket.sendFrame(frame);
// Failed to construct a message.
return null;
}
private byte[] getMessage(WebSocketFrame frame)
{
// The raw payload of the frame.
byte[] payload = frame.getPayload();
// If a per-message compression extension is enabled and
// the Per-Message Compressed bit of the frame is set.
if (mPMCE != null && frame.getRsv1())
{
// Decompress the payload.
payload = decompress(payload);
}
return payload;
}
private byte[] decompress(byte[] input)
{
WebSocketException wse;
try
{
// Decompress the message.
return mPMCE.decompress(input);
}
catch (WebSocketException e)
{
wse = e;
}
// Notify the listeners that decompression failed.
callOnError(wse);
callOnMessageDecompressionError(wse, input);
// Create a close frame with a close code of 1003 which
// indicates that the message cannot be accepted.
WebSocketFrame frame = WebSocketFrame
.createCloseFrame(WebSocketCloseCode.UNACCEPTABLE, wse.getMessage());
// Send the close frame.
mWebSocket.sendFrame(frame);
// Failed to construct a message.
return null;
}
private boolean handleTextFrame(WebSocketFrame frame)
{
// Notify the listeners that a text frame was received.
callOnTextFrame(frame);
// If the frame indicates the start of fragmentation.
if (frame.getFin() == false)
{
// Start a continuation sequence.
mContinuation.add(frame);
// Keep reading.
return true;
}
// Get the payload of the frame. Decompression is performed
// when necessary.
byte[] payload = getMessage(frame);
// Notify the listeners that a text message was received.
callOnTextMessage(payload);
// Keep reading.
return true;
}
private boolean handleBinaryFrame(WebSocketFrame frame)
{
// Notify the listeners that a binary frame was received.
callOnBinaryFrame(frame);
// If the frame indicates the start of fragmentation.
if (frame.getFin() == false)
{
// Start a continuation sequence.
mContinuation.add(frame);
// Keep reading.
return true;
}
// Get the payload of the frame. Decompression is performed
// when necessary.
byte[] payload = getMessage(frame);
// Notify the listeners that a binary message was received.
callOnBinaryMessage(payload);
// Keep reading.
return true;
}