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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
/*
 * 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 NeoVisionaries.WebSockets;


import static NeoVisionaries.WebSockets.WebSocketState.CLOSED;
import static NeoVisionaries.WebSockets.WebSocketState.CLOSING;
import static NeoVisionaries.WebSockets.WebSocketState.CONNECTING;
import static NeoVisionaries.WebSockets.WebSocketState.CREATED;
import static NeoVisionaries.WebSockets.WebSocketState.OPEN;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;

import NeoVisionaries.WebSockets.StateManager.CloseInitiator;


/**
 * WebSocket.
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=LICENSE><BR />
 *
 * <h3>Create WebSocketFactory</h3>
 *
 * <p>
 * {@link WebSocketFactory} is a factory class that creates
 * {@link WebSocket} instances. The first step is to create a
 * {@code WebSocketFactory} instance.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a WebSocketFactory instance.</span>
 * WebSocketFactory factory = new {@link WebSocketFactory#WebSocketFactory()
 * WebSocketFactory()};</pre>
 * </blockquote>
 *
 * <p>
 * By default, {@code WebSocketFactory} uses {@link
 * javax.net.SocketFactory SocketFactory}{@code .}{@link
 * javax.net.SocketFactory#getDefault() getDefault()} for
 * non-secure WebSocket connections ({@code ws:}) and {@link
 * javax.net.ssl.SSLSocketFactory SSLSocketFactory}{@code
 * .}{@link javax.net.ssl.SSLSocketFactory#getDefault()
 * getDefault()} for secure WebSocket connections ({@code
 * wss:}). You can change this default behavior by using
 * {@code WebSocketFactory.}{@link
 * WebSocketFactory#setSocketFactory(javax.net.SocketFactory)
 * setSocketFactory} method, {@code WebSocketFactory.}{@link
 * WebSocketFactory#setSSLSocketFactory(javax.net.ssl.SSLSocketFactory)
 * setSSLSocketFactory} method and {@code WebSocketFactory.}{@link
 * WebSocketFactory#setSSLContext(javax.net.ssl.SSLContext)
 * setSSLContext} method. Note that you don't have to call a {@code
 * setSSL*} method at all if you use the default SSL configuration.
 * Also note that calling {@code setSSLSocketFactory} method has no
 * meaning if you have called {@code setSSLContext} method. See the
 * description of {@code WebSocketFactory.}{@link
 * WebSocketFactory#createSocket(URI) createSocket(URI)} method for
 * details.
 * </p>
 *
 * <p>
 * The following is an example to set a custom SSL context to a
 * {@code WebSocketFactory} instance. (Again, you don't have to call a
 * {@code setSSL*} method if you use the default SSL configuration.)
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a custom SSL context.</span>
 * SSLContext context = <a href="https://gist.github.com/TakahikoKawasaki/d07de2218b4b81bf65ac"
 * >NaiveSSLContext</a>.getInstance(<span style="color:darkred;">"TLS"</span>);
 *
 * <span style="color: green;">// Set the custom SSL context.</span>
 * factory.{@link WebSocketFactory#setSSLContext(javax.net.ssl.SSLContext)
 * setSSLContext}(context);
 *
 * <span style="color: green;">// Disable manual hostname verification for NaiveSSLContext.
 * //
 * // Manual hostname verification has been enabled since the
 * // version 2.1. Because the verification is executed manually
 * // after Socket.connect(SocketAddress, int) succeeds, the
 * // hostname verification is always executed even if you has
 * // passed an SSLContext which naively accepts any server
 * // certificate. However, this behavior is not desirable in
 * // some cases and you may want to disable the hostname
 * // verification. You can disable the hostname verification
 * // by calling WebSocketFactory.setVerifyHostname(false).</span>
 * factory.{@link WebSocketFactory#setVerifyHostname(boolean) setVerifyHostname}(false);</pre>
 * </blockquote>
 *
 * <p>
 * <a href="https://gist.github.com/TakahikoKawasaki/d07de2218b4b81bf65ac"
 * >NaiveSSLContext</a> used in the above example is a factory class to
 * create an {@link javax.net.ssl.SSLContext SSLContext} which naively
 * accepts all certificates without verification. It's enough for testing
 * purposes. When you see an error message
 * "unable to find valid certificate path to requested target" while
 * testing, try {@code NaiveSSLContext}.
 * </p>
 *
 * <h3>HTTP Proxy</h3>
 *
 * <p>
 * If a WebSocket endpoint needs to be accessed via an HTTP proxy,
 * information about the proxy server has to be set to a {@code
 * WebSocketFactory} instance before creating a {@code WebSocket}
 * instance. Proxy settings are represented by {@link ProxySettings}
 * class. A {@code WebSocketFactory} instance has an associated
 * {@code ProxySettings} instance and it can be obtained by calling
 * {@code WebSocketFactory.}{@link WebSocketFactory#getProxySettings()
 * getProxySettings()} method.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Get the associated ProxySettings instance.</span>
 * {@link ProxySettings} settings = factory.{@link
 * WebSocketFactory#getProxySettings() getProxySettings()};</pre>
 * </blockquote>
 *
 * <p>
 * {@code ProxySettings} class has methods to set information about
 * a proxy server such as {@link ProxySettings#setHost(String) setHost}
 * method and {@link ProxySettings#setPort(int) setPort} method. The
 * following is an example to set a secure (<code>https</code>) proxy
 * server.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Set a proxy server.</span>
 * settings.{@link ProxySettings#setServer(String)
 * setServer}(<span style="color:darkred;">"https://proxy.example.com"</span>);</pre>
 * </blockquote>
 *
 * <p>
 * If credentials are required for authentication at a proxy server,
 * {@link ProxySettings#setId(String) setId} method and {@link
 * ProxySettings#setPassword(String) setPassword} method, or
 * {@link ProxySettings#setCredentials(String, String) setCredentials}
 * method can be used to set the credentials. Note that, however,
 * the current implementation supports only Basic Authentication.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Set credentials for authentication at a proxy server.</span>
 * settings.{@link ProxySettings#setCredentials(String, String)
 * setCredentials}(id, password);
 * </pre>
 * </blockquote>
 *
 * <h3>Create WebSocket</h3>
 *
 * <p>
 * {@link WebSocket} class represents a WebSocket. Its instances are
 * created by calling one of {@code createSocket} methods of a {@link
 * WebSocketFactory} instance. Below is the simplest example to create
 * a {@code WebSocket} instance.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a WebSocket. The scheme part can be one of the following:
 * // 'ws', 'wss', 'http' and 'https' (case-insensitive). The user info
 * // part, if any, is interpreted as expected. If a raw socket failed
 * // to be created, an IOException is thrown.</span>
 * WebSocket ws = new {@link WebSocketFactory#WebSocketFactory()
 * WebSocketFactory()}
 *     .{@link WebSocketFactory#createSocket(String)
 * createWebSocket}(<span style="color: darkred;">"ws://localhost/endpoint"</span>);</pre>
 * </blockquote>
 *
 * <p>
 * There are two ways to set a timeout value for socket connection. The
 * first way is to call {@link WebSocketFactory#setConnectionTimeout(int)
 * setConnectionTimeout(int timeout)} method of {@code WebSocketFactory}.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a WebSocket factory and set 5000 milliseconds as a timeout
 * // value for socket connection.</span>
 * WebSocketFactory factory = new WebSocketFactory().{@link
 * WebSocketFactory#setConnectionTimeout(int) setConnectionTimeout}(5000);
 *
 * <span style="color: green;">// Create a WebSocket. The timeout value set above is used.</span>
 * WebSocket ws = factory.{@link WebSocketFactory#createSocket(String)
 * createWebSocket}(<span style="color: darkred;">"ws://localhost/endpoint"</span>);</pre>
 * </blockquote>
 *
 * <p>
 * The other way is to give a timeout value to a {@code createSocket} method.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a WebSocket factory. The timeout value remains 0.</span>
 * WebSocketFactory factory = new WebSocketFactory();
 *
 * <span style="color: green;">// Create a WebSocket with a socket connection timeout value.</span>
 * WebSocket ws = factory.{@link WebSocketFactory#createSocket(String, int)
 * createWebSocket}(<span style="color: darkred;">"ws://localhost/endpoint"</span>, 5000);</pre>
 * </blockquote>
 *
 * <p>
 * The timeout value is passed to {@link Socket#connect(java.net.SocketAddress, int)
 * connect}{@code (}{@link java.net.SocketAddress SocketAddress}{@code , int)}
 * method of {@link java.net.Socket}.
 * </p>
 *
 * <h3>Register Listener</h3>
 *
 * <p>
 * After creating a {@code WebSocket} instance, you should call {@link
 * #addListener(WebSocketListener)} method to register a {@link
 * WebSocketListener} that receives WebSocket events. {@link
 * WebSocketAdapter} is an empty implementation of {@link
 * WebSocketListener} interface.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Register a listener to receive WebSocket events.</span>
 * ws.{@link #addListener(WebSocketListener) addListener}(new {@link
 * WebSocketAdapter#WebSocketAdapter() WebSocketAdapter()} {
 *     <span style="color: gray;">{@code @}Override</span>
 *     public void {@link WebSocketListener#onTextMessage(WebSocket, String)
 *     onTextMessage}(WebSocket websocket, String message) throws Exception {
 *         <span style="color: green;">// Received a text message.</span>
 *         ......
 *     }
 * });</pre>
 * </blockquote>
 *
 * <p>
 * The table below is the list of callback methods defined in {@code WebSocketListener}
 * interface.
 * </p>
 *
 * <blockquote>
 * <table border="1" cellpadding="5" style="border-collapse: collapse;">
 *   <caption>{@code WebSocketListener} methods</caption>
 *   <thead>
 *     <tr>
 *       <th>Method</th>
 *       <th>Description</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td>{@link WebSocketListener#handleCallbackError(WebSocket, Throwable) handleCallbackError}</td>
 *       <td>Called when an <code>on<i>Xxx</i>()</code> method threw a {@code Throwable}.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onBinaryFrame(WebSocket, WebSocketFrame) onBinaryFrame}</td>
 *       <td>Called when a binary frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onBinaryMessage(WebSocket, byte[]) onBinaryMessage}</td>
 *       <td>Called when a binary message was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onCloseFrame(WebSocket, WebSocketFrame) onCloseFrame}</td>
 *       <td>Called when a close frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onConnected(WebSocket, Map) onConnected}</td>
 *       <td>Called after the opening handshake succeeded.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onConnectError(WebSocket, WebSocketException) onConnectError}</td>
 *       <td>Called when {@link #connectAsynchronously()} failed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onContinuationFrame(WebSocket, WebSocketFrame) onContinuationFrame}</td>
 *       <td>Called when a continuation frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onDisconnected(WebSocket, WebSocketFrame, WebSocketFrame, boolean) onDisconnected}</td>
 *       <td>Called after a WebSocket connection was closed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onError(WebSocket, WebSocketException) onError}</td>
 *       <td>Called when an error occurred.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onFrame(WebSocket, WebSocketFrame) onFrame}</td>
 *       <td>Called when a frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onFrameError(WebSocket, WebSocketException, WebSocketFrame) onFrameError}</td>
 *       <td>Called when a frame failed to be read.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onFrameSent(WebSocket, WebSocketFrame) onFrameSent}</td>
 *       <td>Called when a frame was sent.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onFrameUnsent(WebSocket, WebSocketFrame) onFrameUnsent}</td>
 *       <td>Called when a frame was not sent.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onMessageDecompressionError(WebSocket, WebSocketException, byte[]) onMessageDecompressionError}</td>
 *       <td>Called when a message failed to be decompressed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onMessageError(WebSocket, WebSocketException, List) onMessageError}</td>
 *       <td>Called when a message failed to be constructed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onPingFrame(WebSocket, WebSocketFrame) onPingFrame}</td>
 *       <td>Called when a ping frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onPongFrame(WebSocket, WebSocketFrame) onPongFrame}</td>
 *       <td>Called when a pong frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onSendError(WebSocket, WebSocketException, WebSocketFrame) onSendError}</td>
 *       <td>Called when an error occurred on sending a frame.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onSendingFrame(WebSocket, WebSocketFrame) onSendingFrame}</td>
 *       <td>Called before a frame is sent.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onSendingHandshake(WebSocket, String, List) onSendingHandshake}</td>
 *       <td>Called before an opening handshake is sent.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onStateChanged(WebSocket, WebSocketState) onStateChanged}</td>
 *       <td>Called when the state of WebSocket changed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onTextFrame(WebSocket, WebSocketFrame) onTextFrame}</td>
 *       <td>Called when a text frame was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onTextMessage(WebSocket, String) onTextMessage}</td>
 *       <td>Called when a text message was received.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onTextMessageError(WebSocket, WebSocketException, byte[]) onTextMessageError}</td>
 *       <td>Called when a text message failed to be constructed.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadCreated(WebSocket, ThreadType, Thread) onThreadCreated}</td>
 *       <td>Called after a thread was created.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadStarted(WebSocket, ThreadType, Thread) onThreadStarted}</td>
 *       <td>Called at the beginning of a thread's {@code run()} method.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadStopping(WebSocket, ThreadType, Thread) onThreadStopping}</td>
 *       <td>Called at the end of a thread's {@code run()} method.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onUnexpectedError(WebSocket, WebSocketException) onUnexpectedError}</td>
 *       <td>Called when an uncaught throwable was detected.</td>
 *     </tr>
 *   </tbody>
 * </table>
 * </blockquote>
 *
 * <h3>Configure WebSocket</h3>
 *
 * <p>
 * Before starting a WebSocket <a href="https://tools.ietf.org/html/rfc6455#section-4"
 * >opening handshake</a> with the server, you can configure the
 * {@code WebSocket} instance by using the following methods.
 * </p>
 *
 * <blockquote>
 * <table border="1" cellpadding="5" style="border-collapse: collapse;">
 *   <caption>Methods for Configuration</caption>
 *   <thead>
 *     <tr>
 *       <th>METHOD</th>
 *       <th>DESCRIPTION</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td>{@link #addProtocol(String) addProtocol}</td>
 *       <td>Adds an element to {@code Sec-WebSocket-Protocol}</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #addExtension(WebSocketExtension) addExtension}</td>
 *       <td>Adds an element to {@code Sec-WebSocket-Extensions}</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #addHeader(String, String) addHeader}</td>
 *       <td>Adds an arbitrary HTTP header.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #setUserInfo(String, String) setUserInfo}</td>
 *       <td>Adds {@code Authorization} header for Basic Authentication.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #getSocket() getSocket}</td>
 *       <td>
 *         Gets the underlying {@link Socket} instance to configure it.
 *         Note that this may return {@code null} since version 2.9.
 *         Consider using {@link #getConnectedSocket()} as necessary.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>{@link #getConnectedSocket() getConnectedSocket}</td>
 *       <td>
 *         Establishes and gets the underlying Socket instance to configure it.
 *         Available since version 2.9.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>{@link #setExtended(boolean) setExtended}</td>
 *       <td>Disables validity checks on RSV1/RSV2/RSV3 and opcode.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #setFrameQueueSize(int) setFrameQueueSize}</td>
 *       <td>Set the size of the frame queue for <a href="#congestion_control">congestion control</a>.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #setMaxPayloadSize(int) setMaxPayloadSize}</td>
 *       <td>Set the <a href="#maximum_payload_size">maximum payload size</a>.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link #setMissingCloseFrameAllowed(boolean) setMissingCloseFrameAllowed}</td>
 *       <td>Set whether to allow the server to close the connection without sending a close frame.</td>
 *     </tr>
 *   </tbody>
 * </table>
 * </blockquote>
 *
 * <h3>Connect To Server</h3>
 *
 * <p>
 * By calling {@link #connect()} method, connection to the server is
 * established and a WebSocket opening handshake is performed
 * synchronously. If an error occurred during the handshake,
 * a {@link WebSocketException} would be thrown. Instead, when the
 * handshake succeeds, the {@code connect()} implementation creates
 * threads and starts them to read and write WebSocket frames
 * asynchronously.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> try
 * {
 *     <span style="color: green;">// Connect to the server and perform an opening handshake.</span>
 *     <span style="color: green;">// This method blocks until the opening handshake is finished.</span>
 *     ws.{@link #connect()};
 * }
 * catch ({@link OpeningHandshakeException} e)
 * {
 *     <span style="color: green;">// A violation against the WebSocket protocol was detected</span>
 *     <span style="color: green;">// during the opening handshake.</span>
 * }
 * catch ({@link HostnameUnverifiedException} e)
 * {
 *     <span style="color: green;">// The certificate of the peer does not match the expected hostname.</span>
 * }
 * catch ({@link WebSocketException} e)
 * {
 *     <span style="color: green;">// Failed to establish a WebSocket connection.</span>
 * }</pre>
 * </blockquote>
 *
 * <p>
 * In some cases, {@code connect()} method throws {@link OpeningHandshakeException}
 * which is a subclass of {@code WebSocketException} (since version 1.19).
 * {@code OpeningHandshakeException} provides additional methods such as
 * {@link OpeningHandshakeException#getStatusLine() getStatusLine()},
 * {@link OpeningHandshakeException#getHeaders() getHeaders()} and
 * {@link OpeningHandshakeException#getBody() getBody()} to access the
 * response from a server. The following snippet is an example to print
 * information that the exception holds.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> catch ({@link OpeningHandshakeException} e)
 * {
 *     <span style="color: green;">// Status line.</span>
 *     {@link StatusLine} sl = e.{@link OpeningHandshakeException#getStatusLine() getStatusLine()};
 *     System.out.println(<span style="color:darkred;">"=== Status Line ==="</span>);
 *     System.out.format(<span style="color:darkred;">"HTTP Version  = %s\n"</span>, sl.{@link StatusLine#getHttpVersion() getHttpVersion()});
 *     System.out.format(<span style="color:darkred;">"Status Code   = %d\n"</span>, sl.{@link StatusLine#getStatusCode() getStatusCode()});
 *     System.out.format(<span style="color:darkred;">"Reason Phrase = %s\n"</span>, sl.{@link StatusLine#getReasonPhrase() getReasonPhrase()});
 *
 *     <span style="color: green;">// HTTP headers.</span>
 *     Map&lt;String, List&lt;String&gt;&gt; headers = e.{@link OpeningHandshakeException#getHeaders() getHeaders()};
 *     System.out.println(<span style="color:darkred;">"=== HTTP Headers ==="</span>);
 *     for (Map.Entry&lt;String, List&lt;String&gt;&gt; entry : headers.entrySet())
 *     {
 *         <span style="color: green;">// Header name.</span>
 *         String name = entry.getKey();
 *
 *         <span style="color: green;">// Values of the header.</span>
 *         List&lt;String&gt; values = entry.getValue();
 *
 *         if (values == null || values.size() == 0)
 *         {
 *             <span style="color: green;">// Print the name only.</span>
 *             System.out.println(name);
 *             continue;
 *         }
 *
 *         for (String value : values)
 *         {
 *             <span style="color: green;">// Print the name and the value.</span>
 *             System.out.format(<span style="color:darkred;">"%s: %s\n"</span>, name, value);
 *         }
 *     }
 * }</pre>
 * </blockquote>
 *
 * <p>
 * Also, {@code connect()} method throws {@link HostnameUnverifiedException}
 * which is a subclass of {@code WebSocketException} (since version 2.1) when
 * the certificate of the peer does not match the expected hostname.
 * </p>
 *
 * <h3>Connect To Server Asynchronously</h3>
 *
 * <p>
 * The simplest way to call {@code connect()} method asynchronously is to
 * use {@link #connectAsynchronously()} method. The implementation of the
 * method creates a thread and calls {@code connect()} method in the thread.
 * When the {@code connect()} call failed, {@link
 * WebSocketListener#onConnectError(WebSocket, WebSocketException)
 * onConnectError()} of {@code WebSocketListener} would be called. Note that
 * {@code onConnectError()} is called only when {@code connectAsynchronously()}
 * was used and the {@code connect()} call executed in the background thread
 * failed. Neither direct synchronous {@code connect()} nor
 * {@link WebSocket#connect(java.util.concurrent.ExecutorService)
 * connect(ExecutorService)} (described below) will trigger the callback method.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Connect to the server asynchronously.</span>
 * ws.{@link #connectAsynchronously()};
 * </pre>
 * </blockquote>
 *
 * <p>
 * Another way to call {@code connect()} method asynchronously is to use
 * {@link #connect(ExecutorService)} method. The method performs a WebSocket
 * opening handshake asynchronously using the given {@link ExecutorService}.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Prepare an ExecutorService.</span>
 * {@link ExecutorService} es = {@link java.util.concurrent.Executors Executors}.{@link
 * java.util.concurrent.Executors#newSingleThreadExecutor() newSingleThreadExecutor()};
 *
 * <span style="color: green;">// Connect to the server asynchronously.</span>
 * {@link Future}{@code <WebSocket>} future = ws.{@link #connect(ExecutorService) connect}(es);
 *
 * try
 * {
 *     <span style="color: green;">// Wait for the opening handshake to complete.</span>
 *     future.get();
 * }
 * catch ({@link java.util.concurrent.ExecutionException ExecutionException} e)
 * {
 *     if (e.getCause() instanceof {@link WebSocketException})
 *     {
 *         ......
 *     }
 * }</pre>
 * </blockquote>
 *
 * <p>
 * The implementation of {@code connect(ExecutorService)} method creates
 * a {@link java.util.concurrent.Callable Callable}{@code <WebSocket>}
 * instance by calling {@link #connectable()} method and passes the
 * instance to {@link ExecutorService#submit(Callable) submit(Callable)}
 * method of the given {@code ExecutorService}. What the implementation
 * of {@link Callable#call() call()} method of the {@code Callable}
 * instance does is just to call the synchronous {@code connect()}.
 * </p>
 *
 * <h3>Send Frames</h3>
 *
 * <p>
 * WebSocket frames can be sent by {@link #sendFrame(WebSocketFrame)}
 * method. Other <code>send<i>Xxx</i></code> methods such as {@link
 * #sendText(String)} are aliases of {@code sendFrame} method. All of
 * the <code>send<i>Xxx</i></code> methods work asynchronously.
 * However, under some conditions, <code>send<i>Xxx</i></code> methods
 * may block. See <a href="#congestion_control">Congestion Control</a>
 * for details.
 * </p>
 *
 * <p>
 * Below
 * are some examples of <code>send<i>Xxx</i></code> methods. Note that
 * in normal cases, you don't have to call {@link #sendClose()} method
 * and {@link #sendPong()} (or their variants) explicitly because they
 * are called automatically when appropriate.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Send a text frame.</span>
 * ws.{@link #sendText(String) sendText}(<span style="color: darkred;">"Hello."</span>);
 *
 * <span style="color: green;">// Send a binary frame.</span>
 * byte[] binary = ......;
 * ws.{@link #sendBinary(byte[]) sendBinary}(binary);
 *
 * <span style="color: green;">// Send a ping frame.</span>
 * ws.{@link #sendPing(String) sendPing}(<span style="color: darkred;">"Are you there?"</span>);</pre>
 * </blockquote>
 *
 * <p>
 * If you want to send fragmented frames, you have to know the details
 * of the specification (<a href="https://tools.ietf.org/html/rfc6455#section-5.4"
 * >5.4. Fragmentation</a>). Below is an example to send a text message
 * ({@code "How are you?"}) which consists of 3 fragmented frames.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// The first frame must be either a text frame or a binary frame.
 * // And its FIN bit must be cleared.</span>
 * WebSocketFrame firstFrame = WebSocketFrame
 *     .{@link WebSocketFrame#createTextFrame(String)
 *     createTextFrame}(<span style="color: darkred;">"How "</span>)
 *     .{@link WebSocketFrame#setFin(boolean) setFin}(false);
 *
 * <span style="color: green;">// Subsequent frames must be continuation frames. The FIN bit of
 * // all continuation frames except the last one must be cleared.
 * // Note that the FIN bit of frames returned from
 * // WebSocketFrame.createContinuationFrame methods is cleared, so
 * // the example below does not clear the FIN bit explicitly.</span>
 * WebSocketFrame secondFrame = WebSocketFrame
 *     .{@link WebSocketFrame#createContinuationFrame(String)
 *     createContinuationFrame}(<span style="color: darkred;">"are "</span>);
 *
 * <span style="color: green;">// The last frame must be a continuation frame with the FIN bit set.
 * // Note that the FIN bit of frames returned from
 * // WebSocketFrame.createContinuationFrame methods is cleared, so
 * // the FIN bit of the last frame must be set explicitly.</span>
 * WebSocketFrame lastFrame = WebSocketFrame
 *     .{@link WebSocketFrame#createContinuationFrame(String)
 *     createContinuationFrame}(<span style="color: darkred;">"you?"</span>)
 *     .{@link WebSocketFrame#setFin(boolean) setFin}(true);
 *
 * <span style="color: green;">// Send a text message which consists of 3 frames.</span>
 * ws.{@link #sendFrame(WebSocketFrame) sendFrame}(firstFrame)
 *   .{@link #sendFrame(WebSocketFrame) sendFrame}(secondFrame)
 *   .{@link #sendFrame(WebSocketFrame) sendFrame}(lastFrame);</pre>
 * </blockquote>
 *
 * <p>
 * Alternatively, the same as above can be done like this.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Send a text message which consists of 3 frames.</span>
 * ws.{@link #sendText(String, boolean) sendText}(<span style="color: darkred;">"How "</span>, false)
 *   .{@link #sendContinuation(String) sendContinuation}(<span style="color: darkred;">"are "</span>)
 *   .{@link #sendContinuation(String, boolean) sendContinuation}(<span style="color: darkred;">"you?"</span>, true);</pre>
 * </blockquote>
 *
 * <h3>Send Ping/Pong Frames Periodically</h3>
 *
 * <p>
 * You can send ping frames periodically by calling {@link #setPingInterval(long)
 * setPingInterval} method with an interval in milliseconds between ping frames.
 * This method can be called both before and after {@link #connect()} method.
 * Passing zero stops the periodical sending.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Send a ping per 60 seconds.</span>
 * ws.{@link #setPingInterval(long) setPingInterval}(60 * 1000);
 *
 * <span style="color: green;">// Stop the periodical sending.</span>
 * ws.{@link #setPingInterval(long) setPingInterval}(0);</pre>
 * </blockquote>
 *
 * <p>
 * Likewise, you can send pong frames periodically by calling {@link
 * #setPongInterval(long) setPongInterval} method. "<i>A Pong frame MAY be sent
 * <b>unsolicited</b>."</i> (<a href="https://tools.ietf.org/html/rfc6455#section-5.5.3"
 * >RFC 6455, 5.5.3. Pong</a>)
 * </p>
 *
 * <p>
 * You can customize payload of ping/pong frames that are sent automatically by using
 * {@link #setPingPayloadGenerator(PayloadGenerator)} and
 * {@link #setPongPayloadGenerator(PayloadGenerator)} methods. Both methods take an
 * instance of {@link PayloadGenerator} interface. The following is an example to
 * use the string representation of the current date as payload of ping frames.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> ws.{@link #setPingPayloadGenerator(PayloadGenerator)
 * setPingPayloadGenerator}(new {@link PayloadGenerator} () {
 *     <span style="color: gray;">{@code @}Override</span>
 *     public byte[] generate() {
 *         <span style="color: green;">// The string representation of the current date.</span>
 *         return new Date().toString().getBytes();
 *     }
 * });</pre>
 * </blockquote>
 *
 * <p>
 * Note that the maximum payload length of control frames (e.g. ping frames) is 125.
 * Therefore, the length of a byte array returned from {@link PayloadGenerator#generate()
 * generate()} method must not exceed 125.
 * </p>
 *
 * <p>
 * You can change the names of the {@link java.util.Timer Timer}s that send ping/pong
 * frames periodically by using {@link #setPingSenderName(String)} and
 * {@link #setPongSenderName(String)} methods.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Change the Timers' names.</span>
 * ws.{@link #setPingSenderName(String)
 * setPingSenderName}(<span style="color: darkred;">"PING_SENDER"</span>);
 * ws.{@link #setPongSenderName(String)
 * setPongSenderName}(<span style="color: darkred;">"PONG_SENDER"</span>);
 * </pre>
 * </blockquote>
 *
 * <h3>Auto Flush</h3>
 *
 * <p>
 * By default, a frame is automatically flushed to the server immediately after
 * {@link #sendFrame(WebSocketFrame) sendFrame} method is executed. This automatic
 * flush can be disabled by calling {@link #setAutoFlush(boolean) setAutoFlush}{@code
 * (false)}.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Disable auto-flush.</span>
 * ws.{@link #setAutoFlush(boolean) setAutoFlush}(false);</pre>
 * </blockquote>
 *
 * <p>
 * To flush frames manually, call {@link #flush()} method. Note that this method
 * works asynchronously.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Flush frames to the server manually.</span>
 * ws.{@link #flush()};</pre>
 * </blockquote>
 *
 * <h3 id="congestion_control">Congestion Control</h3>
 *
 * <p>
 * <code>send<i>Xxx</i></code> methods queue a {@link WebSocketFrame} instance to the
 * internal queue. By default, no upper limit is imposed on the queue size, so
 * <code>send<i>Xxx</i></code> methods do not block. However, this behavior may cause
 * a problem if your WebSocket client application sends too many WebSocket frames in
 * a short time for the WebSocket server to process. In such a case, you may want
 * <code>send<i>Xxx</i></code> methods to block when many frames are queued.
 * </p>
 *
 * <p>
 * You can set an upper limit on the internal queue by calling {@link #setFrameQueueSize(int)}
 * method. As a result, if the number of frames in the queue has reached the upper limit
 * when a <code>send<i>Xxx</i></code> method is called, the method blocks until the
 * queue gets spaces. The code snippet below is an example to set 5 as the upper limit
 * of the internal frame queue.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Set 5 as the frame queue size.</span>
 * ws.{@link #setFrameQueueSize(int) setFrameQueueSize}(5);</pre>
 * </blockquote>
 *
 * <p>
 * Note that under some conditions, even if the queue is full, <code>send<i>Xxx</i></code>
 * methods do not block. For example, in the case where the thread to send frames
 * ({@code WritingThread}) is going to stop or has already stopped. In addition,
 * method calls to send a <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
 * >control frame</a> (e.g. {@link #sendClose()} and {@link #sendPing()}) do not block.
 * </p>
 *
 * <h3 id="maximum_payload_size">Maximum Payload Size</h3>
 *
 * <p>
 * You can set an upper limit on the payload size of WebSocket frames by calling
 * {@link #setMaxPayloadSize(int)} method with a positive value. Text, binary and
 * continuation frames whose payload size is bigger than the maximum payload size
 * you have set will be split into multiple frames.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Set 1024 as the maximum payload size.</span>
 * ws.{@link #setMaxPayloadSize(int) setMaxPayloadSize}(1024);</pre>
 * </blockquote>
 *
 * <p>
 * Control frames (close, ping and pong frames) are never split as per the specification.
 * </p>
 *
 * <p>
 * If permessage-deflate extension is enabled and if the payload size of a WebSocket
 * frame after compression does not exceed the maximum payload size, the WebSocket
 * frame is not split even if the payload size before compression execeeds the
 * maximum payload size.
 * </p>
 *
 * <h3 id="compression">Compression</h3>
 *
 * <p>
 * The <strong>permessage-deflate</strong> extension (<a href=
 * "http://tools.ietf.org/html/rfc7692">RFC 7692</a>) has been supported
 * since the version 1.17. To enable the extension, call {@link #addExtension(String)
 * addExtension} method with {@code "permessage-deflate"}.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"><span style="color: green;"> // Enable "permessage-deflate" extension (RFC 7692).</span>
 * ws.{@link #addExtension(String) addExtension}({@link WebSocketExtension#PERMESSAGE_DEFLATE});</pre>
 * </blockquote>
 *
 * <h3>Missing Close Frame</h3>
 *
 * <p>
 * Some server implementations close a WebSocket connection without sending a
 * <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a> to
 * a client in some cases. Strictly speaking, this is a violation against the
 * specification (<a href=
 * "https://tools.ietf.org/html/rfc6455#section-5.5.1">RFC 6455</a>). However, this
 * library has allowed the behavior by default since the version 1.29. Even if the
 * end of the input stream of a WebSocket connection were reached without a close
 * frame being received, it would trigger neither {@link
 * WebSocketListener#onError(WebSocket, WebSocketException) onError()} method nor
 * {@link WebSocketListener#onFrameError(WebSocket, WebSocketException, WebSocketFrame)
 * onFrameError()} method of {@link WebSocketListener}. If you want to make a
 * {@code WebSocket} instance report an error in the case, pass {@code false} to
 * {@link #setMissingCloseFrameAllowed(boolean)} method.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"><span style="color: green;"
 * > // Make this library report an error when the end of the input stream
 * // of the WebSocket connection is reached before a close frame is read.</span>
 * ws.{@link #setMissingCloseFrameAllowed(boolean) setMissingCloseFrameAllowed}(false);</pre>
 * </blockquote>
 *
 * <h3>Direct Text Message</h3>
 *
 * <p>
 * When a text message was received, {@link WebSocketListener#onTextMessage(WebSocket, String)
 * onTextMessage(WebSocket, String)} is called. The implementation internally converts
 * the byte array of the text message into a {@code String} object before calling the
 * listener method. If you want to receive the byte array directly without the string
 * conversion, call {@link #setDirectTextMessage(boolean)} with {@code true}, and
 * {@link WebSocketListener#onTextMessage(WebSocket, byte[]) onTextMessage(WebSocket, byte[])}
 * will be called instead.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"><span style="color: green;"
 * > // Receive text messages without string conversion.</span>
 * ws.{@link #setDirectTextMessage(boolean) setDirectTextMessage}(true);</pre>
 * </blockquote>
 *
 * <h3>Disconnect WebSocket</h3>
 *
 * <p>
 * Before a WebSocket is closed, a closing handshake is performed. A closing handshake
 * is started (1) when the server sends a close frame to the client or (2) when the
 * client sends a close frame to the server. You can start a closing handshake by calling
 * {@link #disconnect()} method (or by sending a close frame manually).
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Close the WebSocket connection.</span>
 * ws.{@link #disconnect()};</pre>
 * </blockquote>
 *
 * <p>
 * {@code disconnect()} method has some variants. If you want to change the close code
 * and the reason phrase of the close frame that this client will send to the server,
 * use a variant method such as {@link #disconnect(int, String)}. {@code disconnect()}
 * method itself is an alias of {@code disconnect(}{@link WebSocketCloseCode}{@code
 * .NORMAL, null)}.
 * </p>
 *
 * <h3>Reconnection</h3>
 *
 * <p>
 * {@code connect()} method can be called at most only once regardless of whether the
 * method succeeded or failed. If you want to re-connect to the WebSocket endpoint,
 * you have to create a new {@code WebSocket} instance again by calling one of {@code
 * createSocket} methods of a {@code WebSocketFactory}. You may find {@link #recreate()}
 * method useful if you want to create a new {@code WebSocket} instance that has the
 * same settings as the original instance. Note that, however, settings you made on
 * the raw socket of the original {@code WebSocket} instance are not copied.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: green;">// Create a new WebSocket instance and connect to the same endpoint.</span>
 * ws = ws.{@link #recreate()}.{@link #connect()};</pre>
 * </blockquote>
 *
 * <p>
 * There is a variant of {@code recreate()} method that takes a timeout value for
 * socket connection. If you want to use a timeout value that is different from the
 * one used when the existing {@code WebSocket} instance was created, use {@link
 * #recreate(int) recreate(int timeout)} method.
 * </p>
 *
 * <p>
 * Note that you should not trigger reconnection in {@link
 * WebSocketListener#onError(WebSocket, WebSocketException) onError()} method
 * because {@code onError()} may be called multiple times due to one error. Instead,
 * {@link WebSocketListener#onDisconnected(WebSocket, WebSocketFrame, WebSocketFrame,
 * boolean) onDisconnected()} is the right place to trigger reconnection.
 * </p>
 *
 * <p>
 * Also note that the reason I use an expression of <i>"to trigger reconnection"</i>
 * instead of <i>"to call <code>recreate().connect()</code>"</i> is that I myself
 * won't do it <i>synchronously</i> in <code>WebSocketListener</code> callback
 * methods but will just schedule reconnection or will just go to the top of a kind
 * of <i>application loop</i> that repeats to establish a WebSocket connection until
 * it succeeds.
 * </p>
 *
 * <h3>Error Handling</h3>
 *
 * <p>
 * {@code WebSocketListener} has some {@code onXxxError()} methods such as {@link
 * WebSocketListener#onFrameError(WebSocket, WebSocketException, WebSocketFrame)
 * onFrameError()} and {@link
 * WebSocketListener#onSendError(WebSocket, WebSocketException, WebSocketFrame)
 * onSendError()}. Among such methods, {@link
 * WebSocketListener#onError(WebSocket, WebSocketException) onError()} is a special
 * one. It is always called before any other {@code onXxxError()} is called. For
 * example, in the implementation of {@code run()} method of {@code ReadingThread},
 * {@code Throwable} is caught and {@code onError()} and {@link
 * WebSocketListener#onUnexpectedError(WebSocket, WebSocketException)
 * onUnexpectedError()} are called in this order. The following is the implementation.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: gray;">{@code @}Override</span>
 * public void run()
 * {
 *     try
 *     {
 *         main();
 *     }
 *     catch (Throwable t)
 *     {
 *         <span style="color: green;">// An uncaught throwable was detected in the reading thread.</span>
 *         {@link WebSocketException} cause = new WebSocketException(
 *             {@link WebSocketError}.{@link WebSocketError#UNEXPECTED_ERROR_IN_READING_THREAD UNEXPECTED_ERROR_IN_READING_THREAD},
 *             <span style="color: darkred;">"An uncaught throwable was detected in the reading thread"</span>, t);
 *
 *         <span style="color: green;">// Notify the listeners.</span>
 *         ListenerManager manager = mWebSocket.getListenerManager();
 *         manager.callOnError(cause);
 *         manager.callOnUnexpectedError(cause);
 *     }
 * }</pre>
 * </blockquote>
 *
 * <p>
 * So, you can handle all error cases in {@code onError()} method. However, note
 * that {@code onError()} may be called multiple times for one error cause, so don't
 * try to trigger reconnection in {@code onError()}. Instead, {@link
 * WebSocketListener#onDisconnected(WebSocket, WebSocketFrame, WebSocketFrame, boolean)
 * onDiconnected()} is the right place to trigger reconnection.
 * </p>
 *
 * <p>
 * All {@code onXxxError()} methods receive a {@link WebSocketException} instance
 * as the second argument (the first argument is a {@code WebSocket} instance). The
 * exception class provides {@link WebSocketException#getError() getError()} method
 * which returns a {@link WebSocketError} enum entry. Entries in {@code WebSocketError}
 * enum are possible causes of errors that may occur in the implementation of this
 * library. The error causes are so granular that they can make it easy for you to
 * find the root cause when an error occurs.
 * </p>
 *
 * <p>
 * {@code Throwable}s thrown by implementations of {@code onXXX()} callback methods
 * are passed to {@link WebSocketListener#handleCallbackError(WebSocket, Throwable)
 * handleCallbackError()} of {@code WebSocketListener}.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: gray;">{@code @}Override</span>
 * public void {@link WebSocketListener#handleCallbackError(WebSocket, Throwable)
 * handleCallbackError}(WebSocket websocket, Throwable cause) throws Exception {
 *     <span style="color: green;">// Throwables thrown by onXxx() callback methods come here.</span>
 * }</pre>
 * </blockquote>
 *
 * <h3>Thread Callbacks</h3>
 *
 * <p>
 * Some threads are created internally in the implementation of {@code WebSocket}.
 * Known threads are as follows.
 * </p>
 *
 * <blockquote>
 * <table border="1" cellpadding="5" style="border-collapse: collapse;">
 *   <caption>Internal Threads</caption>
 *   <thead>
 *     <tr>
 *       <th>THREAD TYPE</th>
 *       <th>DESCRIPTION</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td>{@link ThreadType#READING_THREAD READING_THREAD}</td>
 *       <td>A thread which reads WebSocket frames from the server.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link ThreadType#WRITING_THREAD WRITING_THREAD}</td>
 *       <td>A thread which sends WebSocket frames to the server.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link ThreadType#CONNECT_THREAD CONNECT_THREAD}</td>
 *       <td>A thread which calls {@link WebSocket#connect()} asynchronously.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link ThreadType#FINISH_THREAD FINISH_THREAD}</td>
 *       <td>A thread which does finalization of a {@code WebSocket} instance.</td>
 *     </tr>
 *   </tbody>
 * </table>
 * </blockquote>
 *
 * <p>
 * The following callback methods of {@link WebSocketListener} are called according
 * to the life cycle of the threads.
 * </p>
 *
 * <blockquote>
 * <table border="1" cellpadding="5" style="border-collapse: collapse;">
 *   <caption>Thread Callbacks</caption>
 *   <thead>
 *     <tr>
 *       <th>METHOD</th>
 *       <th>DESCRIPTION</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadCreated(WebSocket, ThreadType, Thread) onThreadCreated()}</td>
 *       <td>Called after a thread was created.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadStarted(WebSocket, ThreadType, Thread) onThreadStarted()}</td>
 *       <td>Called at the beginning of the thread's {@code run()} method.</td>
 *     </tr>
 *     <tr>
 *       <td>{@link WebSocketListener#onThreadStopping(WebSocket, ThreadType, Thread) onThreadStopping()}</td>
 *       <td>Called at the end of the thread's {@code run()} method.</td>
 *     </tr>
 *   </tbody>
 * </table>
 * </blockquote>
 *
 * <p>
 * For example, if you want to change the name of the reading thread,
 * implement {@link WebSocketListener#onThreadCreated(WebSocket, ThreadType, Thread)
 * onThreadCreated()} method like below.
 * </p>
 *
 * <blockquote>
 * <pre style="border-left: solid 5px lightgray;"> <span style="color: gray;">{@code @}Override</span>
 * public void {@link WebSocketListener#onThreadCreated(WebSocket, ThreadType, Thread)
 * onThreadCreated}(WebSocket websocket, {@link ThreadType} type, Thread thread)
 * {
 *     if (type == ThreadType.READING_THREAD)
 *     {
 *         thread.setName(<span style="color: darkred;">"READING_THREAD"</span>);
 *     }
 * }</pre>
 * </blockquote>
 *
 * @see <a href="https://tools.ietf.org/html/rfc6455">RFC 6455 (The WebSocket Protocol)</a>
 * @see <a href="https://tools.ietf.org/html/rfc7692">RFC 7692 (Compression Extensions for WebSocket)</a>
 * @see <a href="https://github.com/TakahikoKawasaki/nv-websocket-client">[GitHub] nv-websocket-client</a>
 *
 * @author Takahiko Kawasaki
 */
public class WebSocket
{
    private static final long DEFAULT_CLOSE_DELAY = 10 * 1000L;
    private final WebSocketFactory mWebSocketFactory;
    private final SocketConnector mSocketConnector;
    private final StateManager mStateManager;
    private HandshakeBuilder mHandshakeBuilder;
    private final ListenerManager mListenerManager;
    private final PingSender mPingSender;
    private final PongSender mPongSender;
    private final Object mThreadsLock = new Object();
    private WebSocketInputStream mInput;
    private WebSocketOutputStream mOutput;
    private ReadingThread mReadingThread;
    private WritingThread mWritingThread;
    private Map<String, List<String>> mServerHeaders;
    private List<WebSocketExtension> mAgreedExtensions;
    private String mAgreedProtocol;
    private boolean mExtended;
    private boolean mAutoFlush = true;
    private boolean mMissingCloseFrameAllowed = true;
    private boolean mDirectTextMessage;
    private int mFrameQueueSize;
    private int mMaxPayloadSize;
    private boolean mOnConnectedCalled;
    private Object mOnConnectedCalledLock = new Object();
    private boolean mReadingThreadStarted;
    private boolean mWritingThreadStarted;
    private boolean mReadingThreadFinished;
    private boolean mWritingThreadFinished;
    private WebSocketFrame mServerCloseFrame;
    private WebSocketFrame mClientCloseFrame;
    private PerMessageCompressionExtension mPerMessageCompressionExtension;


    WebSocket(WebSocketFactory factory, boolean secure, String userInfo,
            String host, String path, SocketConnector connector)
    {
        mWebSocketFactory  = factory;
        mSocketConnector   = connector;
        mStateManager      = new StateManager();
        mHandshakeBuilder  = new HandshakeBuilder(secure, userInfo, host, path);
        mListenerManager   = new ListenerManager(this);
        mPingSender        = new PingSender(this, new CounterPayloadGenerator());
        mPongSender        = new PongSender(this, new CounterPayloadGenerator());
    }


    /**
     * Create a new {@code WebSocket} instance that has the same settings
     * as this instance. Note that, however, settings you made on the raw
     * socket are not copied.
     *
     * <p>
     * The {@link WebSocketFactory} instance that you used to create this
     * {@code WebSocket} instance is used again.
     * </p>
     *
     * <p>
     * This method calls {@link #recreate(int)} with the timeout value that
     * was used when this instance was created. If you want to create a
     * socket connection with a different timeout value, use {@link
     * #recreate(int)} method instead.
     * </p>
     *
     * @return
     *         A new {@code WebSocket} instance.
     *
     * @throws IOException
     *         {@link WebSocketFactory#createSocket(URI)} threw an exception.
     *
     * @since 1.6
     */
    public WebSocket recreate() throws IOException
    {
        return recreate(mSocketConnector.getConnectionTimeout());
    }


    /**
     * Create a new {@code WebSocket} instance that has the same settings
     * as this instance. Note that, however, settings you made on the raw
     * socket are not copied.
     *
     * <p>
     * The {@link WebSocketFactory} instance that you used to create this
     * {@code WebSocket} instance is used again.
     * </p>
     *
     * @return
     *         A new {@code WebSocket} instance.
     *
     * @param timeout
     *         The timeout value in milliseconds for socket timeout.
     *         A timeout of zero is interpreted as an infinite timeout.
     *
     * @throws IllegalArgumentException
     *         The given timeout value is negative.
     *
     * @throws IOException
     *         {@link WebSocketFactory#createSocket(URI)} threw an exception.
     *
     * @since 1.10
     */
    public WebSocket recreate(int timeout) throws IOException
    {
        if (timeout < 0)
        {
            throw new IllegalArgumentException("The given timeout value is negative.");
        }

        WebSocket instance = mWebSocketFactory.createSocket(getURI(), timeout);

        // Copy the settings.
        instance.mHandshakeBuilder = new HandshakeBuilder(mHandshakeBuilder);
        instance.setPingInterval(getPingInterval());
        instance.setPongInterval(getPongInterval());
        instance.setPingPayloadGenerator(getPingPayloadGenerator());
        instance.setPongPayloadGenerator(getPongPayloadGenerator());
        instance.mExtended = mExtended;
        instance.mAutoFlush = mAutoFlush;
        instance.mMissingCloseFrameAllowed = mMissingCloseFrameAllowed;
        instance.mDirectTextMessage = mDirectTextMessage;
        instance.mFrameQueueSize = mFrameQueueSize;

        // Copy listeners.
        List<WebSocketListener> listeners = mListenerManager.getListeners();
        synchronized (listeners)
        {
            instance.addListeners(listeners);
        }

        return instance;
    }


    @Override
    protected void finalize() throws Throwable
    {
        if (isInState(CREATED))
        {
            // The raw socket needs to be closed.
            finish();
        }

        super.finalize();
    }


    /**
     * Get the current state of this WebSocket.
     *
     * <p>
     * The initial state is {@link WebSocketState#CREATED CREATED}.
     * When {@link #connect()} is called, the state is changed to
     * {@link WebSocketState#CONNECTING CONNECTING}, and then to
     * {@link WebSocketState#OPEN OPEN} after a successful opening
     * handshake. The state is changed to {@link
     * WebSocketState#CLOSING CLOSING} when a closing handshake
     * is started, and then to {@link WebSocketState#CLOSED CLOSED}
     * when the closing handshake finished.
     * </p>
     *
     * <p>
     * See the description of {@link WebSocketState} for details.
     * </p>
     *
     * @return
     *         The current state.
     *
     * @see WebSocketState
     */
    public WebSocketState getState()
    {
        synchronized (mStateManager)
        {
            return mStateManager.getState();
        }
    }


    /**
     * Check if the current state of this WebSocket is {@link
     * WebSocketState#OPEN OPEN}.
     *
     * @return
     *         {@code true} if the current state is OPEN.
     *
     * @since 1.1
     */
    public boolean isOpen()
    {
        return isInState(OPEN);
    }


    /**
     * Check if the current state is equal to the specified state.
     */
    private boolean isInState(WebSocketState state)
    {
        synchronized (mStateManager)
        {
            return (mStateManager.getState() == state);
        }
    }


    /**
     * Add a value for {@code Sec-WebSocket-Protocol}.
     *
     * @param protocol
     *         A protocol name.
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         The protocol name is invalid. A protocol name must be
     *         a non-empty string with characters in the range U+0021
     *         to U+007E not including separator characters.
     */
    public WebSocket addProtocol(String protocol)
    {
        mHandshakeBuilder.addProtocol(protocol);

        return this;
    }


    /**
     * Remove a protocol from {@code Sec-WebSocket-Protocol}.
     *
     * @param protocol
     *         A protocol name. {@code null} is silently ignored.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket removeProtocol(String protocol)
    {
        mHandshakeBuilder.removeProtocol(protocol);

        return this;
    }


    /**
     * Remove all protocols from {@code Sec-WebSocket-Protocol}.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket clearProtocols()
    {
        mHandshakeBuilder.clearProtocols();

        return this;
    }


    /**
     * Add a value for {@code Sec-WebSocket-Extension}.
     *
     * @param extension
     *         An extension. {@code null} is silently ignored.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket addExtension(WebSocketExtension extension)
    {
        mHandshakeBuilder.addExtension(extension);

        return this;
    }


    /**
     * Add a value for {@code Sec-WebSocket-Extension}. The input string
     * should comply with the format described in <a href=
     * "https://tools.ietf.org/html/rfc6455#section-9.1">9.1. Negotiating
     * Extensions</a> in <a href="https://tools.ietf.org/html/rfc6455"
     * >RFC 6455</a>.
     *
     * @param extension
     *         A string that represents a WebSocket extension. If it does
     *         not comply with RFC 6455, no value is added to {@code
     *         Sec-WebSocket-Extension}.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket addExtension(String extension)
    {
        mHandshakeBuilder.addExtension(extension);

        return this;
    }


    /**
     * Remove an extension from {@code Sec-WebSocket-Extension}.
     *
     * @param extension
     *         An extension to remove. {@code null} is silently ignored.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket removeExtension(WebSocketExtension extension)
    {
        mHandshakeBuilder.removeExtension(extension);

        return this;
    }


    /**
     * Remove extensions from {@code Sec-WebSocket-Extension} by
     * an extension name.
     *
     * @param name
     *         An extension name. {@code null} is silently ignored.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket removeExtensions(String name)
    {
        mHandshakeBuilder.removeExtensions(name);

        return this;
    }


    /**
     * Remove all extensions from {@code Sec-WebSocket-Extension}.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket clearExtensions()
    {
        mHandshakeBuilder.clearExtensions();

        return this;
    }


    /**
     * Add a pair of extra HTTP header.
     *
     * @param name
     *         An HTTP header name. When {@code null} or an empty
     *         string is given, no header is added.
     *
     * @param value
     *         The value of the HTTP header.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket addHeader(String name, String value)
    {
        mHandshakeBuilder.addHeader(name, value);

        return this;
    }


    /**
     * Remove pairs of extra HTTP headers.
     *
     * @param name
     *         An HTTP header name. {@code null} is silently ignored.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket removeHeaders(String name)
    {
        mHandshakeBuilder.removeHeaders(name);

        return this;
    }


    /**
     * Clear all extra HTTP headers.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket clearHeaders()
    {
        mHandshakeBuilder.clearHeaders();

        return this;
    }


    /**
     * Set the credentials to connect to the WebSocket endpoint.
     *
     * @param userInfo
     *         The credentials for Basic Authentication. The format
     *         should be <code><i>id</i>:<i>password</i></code>.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket setUserInfo(String userInfo)
    {
        mHandshakeBuilder.setUserInfo(userInfo);

        return this;
    }


    /**
     * Set the credentials to connect to the WebSocket endpoint.
     *
     * @param id
     *         The ID.
     *
     * @param password
     *         The password.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket setUserInfo(String id, String password)
    {
        mHandshakeBuilder.setUserInfo(id, password);

        return this;
    }


    /**
     * Clear the credentials to connect to the WebSocket endpoint.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket clearUserInfo()
    {
        mHandshakeBuilder.clearUserInfo();

        return this;
    }


    /**
     * Check if extended use of WebSocket frames are allowed.
     *
     * <p>
     * When extended use is allowed, values of RSV1/RSV2/RSV3 bits
     * and opcode of frames are not checked. On the other hand,
     * if not allowed (default), non-zero values for RSV1/RSV2/RSV3
     * bits and unknown opcodes cause an error. In such a case,
     * {@link WebSocketListener#onFrameError(WebSocket,
     * WebSocketException, WebSocketFrame) onFrameError} method of
     * listeners are called and the WebSocket is eventually closed.
     * </p>
     *
     * @return
     *         {@code true} if extended use of WebSocket frames
     *         are allowed.
     */
    public boolean isExtended()
    {
        return mExtended;
    }


    /**
     * Allow or disallow extended use of WebSocket frames.
     *
     * @param extended
     *         {@code true} to allow extended use of WebSocket frames.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket setExtended(boolean extended)
    {
        mExtended = extended;

        return this;
    }


    /**
     * Check if flush is performed automatically after {@link
     * #sendFrame(WebSocketFrame)} is done. The default value is
     * {@code true}.
     *
     * @return
     *         {@code true} if flush is performed automatically.
     *
     * @since 1.5
     */
    public boolean isAutoFlush()
    {
        return mAutoFlush;
    }


    /**
     * Enable or disable auto-flush of sent frames.
     *
     * @param auto
     *         {@code true} to enable auto-flush. {@code false} to
     *         disable it.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.5
     */
    public WebSocket setAutoFlush(boolean auto)
    {
        mAutoFlush = auto;

        return this;
    }


    /**
     * Check if this instance allows the server to close the WebSocket
     * connection without sending a <a href=
     * "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     * to this client. The default value is {@code true}.
     *
     * @return
     *         {@code true} if the configuration allows for the server to
     *         close the WebSocket connection without sending a close frame
     *         to this client. {@code false} if the configuration requires
     *         that an error be reported via
     *         {@link WebSocketListener#onError(WebSocket, WebSocketException)
     *         onError()} method and {@link WebSocketListener#onFrameError(WebSocket,
     *         WebSocketException, WebSocketFrame) onFrameError()} method of
     *         {@link WebSocketListener}.
     *
     * @since 1.29
     */
    public boolean isMissingCloseFrameAllowed()
    {
        return mMissingCloseFrameAllowed;
    }


    /**
     * Set whether to allow the server to close the WebSocket connection
     * without sending a <a href=
     * "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     * to this client.
     *
     * @param allowed
     *         {@code true} to allow the server to close the WebSocket
     *         connection without sending a close frame to this client.
     *         {@code false} to make this instance report an error when the
     *         end of the input stream of the WebSocket connection is reached
     *         before a close frame is read.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.29
     */
    public WebSocket setMissingCloseFrameAllowed(boolean allowed)
    {
        mMissingCloseFrameAllowed = allowed;

        return this;
    }


    /**
     * Check if text messages are passed to listeners without string conversion.
     *
     * <p>
     * If this method returns {@code true}, when a text message is received,
     * {@link WebSocketListener#onTextMessage(WebSocket, byte[])
     * onTextMessage(WebSocket, byte[])} will be called instead of
     * {@link WebSocketListener#onTextMessage(WebSocket, String)
     * onTextMessage(WebSocket, String)}. The purpose of this behavior
     * is to skip internal string conversion which is performed in the
     * implementation of {@code ReadingThread}.
     * </p>
     *
     * @return
     *         {@code true} if text messages are passed to listeners without
     *         string conversion.
     *
     * @since 2.6
     */
    public boolean isDirectTextMessage()
    {
        return mDirectTextMessage;
    }


    /**
     * Set whether to receive text messages directly as byte arrays without
     * string conversion.
     *
     * <p>
     * If {@code true} is set to this property, when a text message is received,
     * {@link WebSocketListener#onTextMessage(WebSocket, byte[])
     * onTextMessage(WebSocket, byte[])} will be called instead of
     * {@link WebSocketListener#onTextMessage(WebSocket, String)
     * onTextMessage(WebSocket, String)}. The purpose of this behavior
     * is to skip internal string conversion which is performed in the
     * implementation of {@code ReadingThread}.
     * </p>
     *
     * @param direct
     *         {@code true} to receive text messages as byte arrays.
     *
     * @return
     *         {@code this} object.
     *
     * @since 2.6
     */
    public WebSocket setDirectTextMessage(boolean direct)
    {
        mDirectTextMessage = direct;

        return this;
    }


    /**
     * Flush frames to the server. Flush is performed asynchronously.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.5
     */
    public WebSocket flush()
    {
        synchronized (mStateManager)
        {
            WebSocketState state = mStateManager.getState();

            if (state != OPEN && state != CLOSING)
            {
                return this;
            }
        }

        // Get the reference to the instance of WritingThread.
        WritingThread wt = mWritingThread;

        // If and only if an instance of WritingThread is available.
        if (wt != null)
        {
            // Request flush.
            wt.queueFlush();
        }

        return this;
    }


    /**
     * Get the size of the frame queue. The default value is 0 and it means
     * there is no limit on the queue size.
     *
     * @return
     *         The size of the frame queue.
     *
     * @since 1.15
     */
    public int getFrameQueueSize()
    {
        return mFrameQueueSize;
    }


    /**
     * Set the size of the frame queue. The default value is 0 and it means
     * there is no limit on the queue size.
     *
     * <p>
     * <code>send<i>Xxx</i></code> methods queue a {@link WebSocketFrame}
     * instance to the internal queue. If the number of frames in the queue
     * has reached the upper limit (which has been set by this method) when
     * a <code>send<i>Xxx</i></code> method is called, the method blocks
     * until the queue gets spaces.
     * </p>
     *
     * <p>
     * Under some conditions, even if the queue is full, <code>send<i>Xxx</i></code>
     * methods do not block. For example, in the case where the thread to send
     * frames ({@code WritingThread}) is going to stop or has already stopped.
     * In addition, method calls to send a <a href=
     * "https://tools.ietf.org/html/rfc6455#section-5.5">control frame</a> (e.g.
     * {@link #sendClose()} and {@link #sendPing()}) do not block.
     * </p>
     *
     * @param size
     *         The queue size. 0 means no limit. Negative numbers are not allowed.
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         {@code size} is negative.
     *
     * @since 1.15
     */
    public WebSocket setFrameQueueSize(int size) throws IllegalArgumentException
    {
        if (size < 0)
        {
            throw new IllegalArgumentException("size must not be negative.");
        }

        mFrameQueueSize = size;

        return this;
    }


    /**
     * Get the maximum payload size. The default value is 0 which means that
     * the maximum payload size is not set and as a result frames are not split.
     *
     * @return
     *         The maximum payload size. 0 means that the maximum payload size
     *         is not set.
     *
     * @since 1.27
     */
    public int getMaxPayloadSize()
    {
        return mMaxPayloadSize;
    }


    /**
     * Set the maximum payload size.
     *
     * <p>
     * Text, binary and continuation frames whose payload size is bigger than
     * the maximum payload size will be split into multiple frames. Note that
     * control frames (close, ping and pong frames) are not split as per the
     * specification even if their payload size exceeds the maximum payload size.
     * </p>
     *
     * @param size
     *         The maximum payload size. 0 to unset the maximum payload size.
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         {@code size} is negative.
     *
     * @since 1.27
     */
    public WebSocket setMaxPayloadSize(int size) throws IllegalArgumentException
    {
        if (size < 0)
        {
            throw new IllegalArgumentException("size must not be negative.");
        }

        mMaxPayloadSize = size;

        return this;
    }


    /**
     * Get the interval of periodical
     * <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">ping</a>
     * frames.
     *
     * @return
     *         The interval in milliseconds.
     *
     * @since 1.2
     */
    public long getPingInterval()
    {
        return mPingSender.getInterval();
    }


    /**
     * Set the interval of periodical
     * <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">ping</a>
     * frames.
     *
     * <p>
     * Setting a positive number starts sending ping frames periodically.
     * Setting zero stops the periodical sending. This method can be called
     * both before and after {@link #connect()} method.
     * </p>
     *
     * @param interval
     *         The interval in milliseconds. A negative value is
     *         regarded as zero.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.2
     */
    public WebSocket setPingInterval(long interval)
    {
        mPingSender.setInterval(interval);

        return this;
    }


    /**
     * Get the interval of periodical
     * <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pong</a>
     * frames.
     *
     * @return
     *         The interval in milliseconds.
     *
     * @since 1.2
     */
    public long getPongInterval()
    {
        return mPongSender.getInterval();
    }


    /**
     * Set the interval of periodical
     * <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pong</a>
     * frames.
     *
     * <p>
     * Setting a positive number starts sending pong frames periodically.
     * Setting zero stops the periodical sending. This method can be called
     * both before and after {@link #connect()} method.
     * </p>
     *
     * <blockquote>
     * <dl>
     * <dt>
     * <span style="font-weight: normal;">An excerpt from <a href=
     * "https://tools.ietf.org/html/rfc6455#section-5.5.3"
     * >RFC 6455, 5.5.3. Pong</a></span>
     * </dt>
     * <dd>
     * <p><i>
     * A Pong frame MAY be sent <b>unsolicited</b>. This serves as a
     * unidirectional heartbeat.  A response to an unsolicited Pong
     * frame is not expected.
     * </i></p>
     * </dd>
     * </dl>
     * </blockquote>
     *
     * @param interval
     *         The interval in milliseconds. A negative value is
     *         regarded as zero.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.2
     */
    public WebSocket setPongInterval(long interval)
    {
        mPongSender.setInterval(interval);

        return this;
    }


    /**
     * Get the generator of payload of ping frames that are sent automatically.
     *
     * @return
     *         The generator of payload ping frames that are sent automatically.
     *
     * @since 1.20
     */
    public PayloadGenerator getPingPayloadGenerator()
    {
        return mPingSender.getPayloadGenerator();
    }


    /**
     * Set the generator of payload of ping frames that are sent automatically.
     *
     * @param generator
     *         The generator of payload ping frames that are sent automatically.
     *
     * @since 1.20
     */
    public WebSocket setPingPayloadGenerator(PayloadGenerator generator)
    {
        mPingSender.setPayloadGenerator(generator);

        return this;
    }


    /**
     * Get the generator of payload of pong frames that are sent automatically.
     *
     * @return
     *         The generator of payload pong frames that are sent automatically.
     *
     * @since 1.20
     */
    public PayloadGenerator getPongPayloadGenerator()
    {
        return mPongSender.getPayloadGenerator();
    }


    /**
     * Set the generator of payload of pong frames that are sent automatically.
     *
     * @param generator
     *         The generator of payload ppng frames that are sent automatically.
     *
     * @since 1.20
     */
    public WebSocket setPongPayloadGenerator(PayloadGenerator generator)
    {
        mPongSender.setPayloadGenerator(generator);

        return this;
    }


    /**
     * Get the name of the {@code Timer} that sends ping frames periodically.
     *
     * @return
     *         The {@code Timer}'s name.
     *
     * @since 2.5
     */
    public String getPingSenderName()
    {
        return mPingSender.getTimerName();
    }


    /**
     * Set the name of the {@code Timer} that sends ping frames periodically.
     *
     * @param name
     *         A name for the {@code Timer}.
     *
     * @return
     *         {@code this} object.
     *
     * @since 2.5
     */
    public WebSocket setPingSenderName(String name)
    {
        mPingSender.setTimerName(name);

        return this;
    }


    /**
     * Get the name of the {@code Timer} that sends pong frames periodically.
     *
     * @return
     *         The {@code Timer}'s name.
     *
     * @since 2.5
     */
    public String getPongSenderName()
    {
        return mPongSender.getTimerName();
    }


    /**
     * Set the name of the {@code Timer} that sends pong frames periodically.
     *
     * @param name
     *         A name for the {@code Timer}.
     *
     * @return
     *         {@code this} object.
     *
     * @since 2.5
     */
    public WebSocket setPongSenderName(String name)
    {
        mPongSender.setTimerName(name);

        return this;
    }


    /**
     * Add a listener to receive events on this WebSocket.
     *
     * @param listener
     *         A listener to add.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket addListener(WebSocketListener listener)
    {
        mListenerManager.addListener(listener);

        return this;
    }


    /**
     * Add listeners.
     *
     * @param listeners
     *         Listeners to add. {@code null} is silently ignored.
     *         {@code null} elements in the list are ignored, too.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket addListeners(List<WebSocketListener> listeners)
    {
        mListenerManager.addListeners(listeners);

        return this;
    }


    /**
     * Remove a listener from this WebSocket.
     *
     * @param listener
     *         A listener to remove. {@code null} won't cause an error.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.13
     */
    public WebSocket removeListener(WebSocketListener listener)
    {
        mListenerManager.removeListener(listener);

        return this;
    }


    /**
     * Remove listeners.
     *
     * @param listeners
     *         Listeners to remove. {@code null} is silently ignored.
     *         {@code null} elements in the list are ignored, too.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.14
     */
    public WebSocket removeListeners(List<WebSocketListener> listeners)
    {
        mListenerManager.removeListeners(listeners);

        return this;
    }


    /**
     * Remove all the listeners from this WebSocket.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.13
     */
    public WebSocket clearListeners()
    {
        mListenerManager.clearListeners();

        return this;
    }


    /**
     * Get the raw socket which this WebSocket uses internally if it has been
     * established, yet.
     *
     * <p>
     * Version 2.9 has changed the behavior of this method, and this method may
     * return {@code null} if the underlying socket has not been established yet.
     * Consider using {@link #getConnectedSocket()} method as necessary.
     * </p>
     *
     * @return
     *         The underlying {@link Socket} instance.
     *         This may be {@code null} in case the underlying socket has not
     *         been established, yet.
     *
     * @see #getConnectedSocket()
     */
    public Socket getSocket()
    {
        return mSocketConnector.getSocket();
    }


    /**
     * Get the raw socket which this WebSocket uses internally. This will
     * establish a connection to the server if not already done.
     *
     * @return
     *         The underlying {@link Socket} instance.
     *
     * @since 2.9
     */
    public Socket getConnectedSocket() throws WebSocketException
    {
        return mSocketConnector.getConnectedSocket();
    }


    /**
     * Get the URI of the WebSocket endpoint. The scheme part is either
     * {@code "ws"} or {@code "wss"}. The authority part is always empty.
     *
     * @return
     *         The URI of the WebSocket endpoint.
     *
     * @since 1.1
     */
    public URI getURI()
    {
        return mHandshakeBuilder.getURI();
    }


    /**
     * Connect to the server, send an opening handshake to the server,
     * receive the response and then start threads to communicate with
     * the server.
     *
     * <p>
     * As necessary, {@link #addProtocol(String)}, {@link #addExtension(WebSocketExtension)}
     * {@link #addHeader(String, String)} should be called before you call this
     * method. It is because the parameters set by these methods are used in the
     * opening handshake.
     * </p>
     *
     * <p>
     * Also, as necessary, {@link #getSocket()} should be used to set up socket
     * parameters before you call this method. For example, you can set the
     * socket timeout like the following. Note that, however, because the version
     * 2.9 changed the behavior of {@link #getSocket()} and the method may return
     * {@code null} if the underlying socket has not been established yet, you may
     * need to use {@link #getConnectedSocket()} method instead.
     * </p>
     *
     * <pre>
     * WebSocket websocket = ......;
     * websocket.{@link #getSocket() getSocket()}.{@link Socket#setSoTimeout(int)
     * setSoTimeout}(5000);
     *
     * <span style="color: green;">// getConnectedSocket() instead of getSocket(), since version 2.9.</span>
     * websocket.{@link #getConnectedSocket() getConnectedSocket()}.{@link
     * Socket#setSoTimeout(int) setSoTimeout}(5000);
     * </pre>
     *
     * <p>
     * If the WebSocket endpoint requires Basic Authentication, you can set
     * credentials by {@link #setUserInfo(String) setUserInfo(userInfo)} or
     * {@link #setUserInfo(String, String) setUserInfo(id, password)} before
     * you call this method.
     * Note that if the URI passed to {@link WebSocketFactory}{@code
     * .createSocket} method contains the user-info part, you don't have to
     * call {@code setUserInfo} method.
     * </p>
     *
     * <p>
     * Note that this method can be called at most only once regardless of
     * whether this method succeeded or failed. If you want to re-connect to
     * the WebSocket endpoint, you have to create a new {@code WebSocket}
     * instance again by calling one of {@code createSocket} methods of a
     * {@link WebSocketFactory}. You may find {@link #recreate()} method
     * useful if you want to create a new {@code WebSocket} instance that
     * has the same settings as this instance. (But settings you made on
     * the raw socket are not copied.)
     * </p>
     *
     * @return
     *         {@code this} object.
     *
     * @throws WebSocketException
     *         <ul>
     *           <li>The current state of the WebSocket is not {@link
     *               WebSocketState#CREATED CREATED}
     *           </li>
     *           <li>Connecting the server failed.</li>
     *           <li>The opening handshake failed.</li>
     *         </ul>
     */
    public WebSocket connect() throws WebSocketException
    {
        // Change the state to CONNECTING. If the state before
        // the change is not CREATED, an exception is thrown.
        changeStateOnConnect();

        // HTTP headers from the server.
        Map<String, List<String>> headers;

        try
        {
            // Connect to the server.
            Socket socket = mSocketConnector.connect();

            // Perform WebSocket handshake.
            headers = shakeHands(socket);
        }
        catch (WebSocketException e)
        {
            // Close the socket.
            mSocketConnector.closeSilently();

            // Change the state to CLOSED.
            mStateManager.setState(CLOSED);

            // Notify the listener of the state change.
            mListenerManager.callOnStateChanged(CLOSED);

            // The handshake failed.
            throw e;
        }

        // HTTP headers in the response from the server.
        mServerHeaders = headers;

        // Extensions.
        mPerMessageCompressionExtension = findAgreedPerMessageCompressionExtension();

        // Change the state to OPEN.
        mStateManager.setState(OPEN);

        // Notify the listener of the state change.
        mListenerManager.callOnStateChanged(OPEN);

        // Start threads that communicate with the server.
        startThreads();

        return this;
    }


    /**
     * Execute {@link #connect()} asynchronously using the given {@link
     * ExecutorService}. This method is just an alias of the following.
     *
     * <blockquote>
     * <code>executorService.{@link ExecutorService#submit(Callable) submit}({@link #connectable()})</code>
     * </blockquote>
     *
     * @param executorService
     *         An {@link ExecutorService} to execute a task created by
     *         {@link #connectable()}.
     *
     * @return
     *         The value returned from {@link ExecutorService#submit(Callable)}.
     *
     * @throws NullPointerException
     *         If the given {@link ExecutorService} is {@code null}.
     *
     * @throws RejectedExecutionException
     *         If the given {@link ExecutorService} rejected the task
     *         created by {@link #connectable()}.
     *
     * @see #connectAsynchronously()
     *
     * @since 1.7
     */
    public Future<WebSocket> connect(ExecutorService executorService)
    {
        return executorService.submit(connectable());
    }


    /**
     * Get a new {@link Callable}{@code <}{@link WebSocket}{@code >} instance
     * whose {@link Callable#call() call()} method calls {@link #connect()}
     * method of this {@code WebSocket} instance.
     *
     * @return
     *         A new {@link Callable}{@code <}{@link WebSocket}{@code >} instance
     *         for asynchronous {@link #connect()}.
     *
     * @see #connect(ExecutorService)
     *
     * @since 1.7
     */
    public Callable<WebSocket> connectable()
    {
        return new Connectable(this);
    }


    /**
     * Execute {@link #connect()} asynchronously by creating a new thread and
     * calling {@code connect()} in the thread. If {@code connect()} failed,
     * {@link WebSocketListener#onConnectError(WebSocket, WebSocketException)
     * onConnectError()} method of {@link WebSocketListener} is called.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.8
     */
    public WebSocket connectAsynchronously()
    {
        Thread thread = new ConnectThread(this);

        // Get the reference (just in case)
        ListenerManager lm = mListenerManager;

        if (lm != null)
        {
            lm.callOnThreadCreated(ThreadType.CONNECT_THREAD, thread);
        }

        thread.start();

        return this;
    }


    /**
     * Disconnect the WebSocket.
     *
     * <p>
     * This method is an alias of {@link #disconnect(int, String)
     * disconnect}{@code (}{@link WebSocketCloseCode#NORMAL}{@code , null)}.
     * </p>
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket disconnect()
    {
        return disconnect(WebSocketCloseCode.NORMAL, null);
    }


    /**
     * Disconnect the WebSocket.
     *
     * <p>
     * This method is an alias of {@link #disconnect(int, String)
     * disconnect}{@code (closeCode, null)}.
     * </p>
     *
     * @param closeCode
     *         The close code embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.5
     */
    public WebSocket disconnect(int closeCode)
    {
        return disconnect(closeCode, null);
    }


    /**
     * Disconnect the WebSocket.
     *
     * <p>
     * This method is an alias of {@link #disconnect(int, String)
     * disconnect}{@code (}{@link WebSocketCloseCode#NORMAL}{@code , reason)}.
     * </p>
     *
     * @param reason
     *         The reason embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server. Note that
     *         the length of the bytes which represents the given reason must
     *         not exceed 125. In other words, {@code (reason.}{@link
     *         String#getBytes(String) getBytes}{@code ("UTF-8").length <= 125)}
     *         must be true.
     *
     * @return
     *         {@code this} object.
     *
     * @since 1.5
     */
    public WebSocket disconnect(String reason)
    {
        return disconnect(WebSocketCloseCode.NORMAL, reason);
    }


    /**
     * Disconnect the WebSocket.
     *
     * <p>
     * This method is an alias of {@link #disconnect(int, String, long)
     * disconnect}{@code (closeCode, reason, 10000L)}.
     * </p>
     *
     * @param closeCode
     *         The close code embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server.
     *
     * @param reason
     *         The reason embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server. Note that
     *         the length of the bytes which represents the given reason must
     *         not exceed 125. In other words, {@code (reason.}{@link
     *         String#getBytes(String) getBytes}{@code ("UTF-8").length <= 125)}
     *         must be true.
     *
     * @return
     *         {@code this} object.
     *
     * @see WebSocketCloseCode
     *
     * @see <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">RFC 6455, 5.5.1. Close</a>
     *
     * @since 1.5
     */
    public WebSocket disconnect(int closeCode, String reason)
    {
        return disconnect(closeCode, reason, DEFAULT_CLOSE_DELAY);
    }


    /**
     * Disconnect the WebSocket.
     *
     * @param closeCode
     *         The close code embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server.
     *
     * @param reason
     *         The reason embedded in a <a href=
     *         "https://tools.ietf.org/html/rfc6455#section-5.5.1">close frame</a>
     *         which this WebSocket client will send to the server. Note that
     *         the length of the bytes which represents the given reason must
     *         not exceed 125. In other words, {@code (reason.}{@link
     *         String#getBytes(String) getBytes}{@code ("UTF-8").length <= 125)}
     *         must be true.
     *
     * @param closeDelay
     *         Delay in milliseconds before calling {@link Socket#close()} forcibly.
     *         This safeguard is needed for the case where the server fails to send
     *         back a close frame. The default value is 10000 (= 10 seconds). When
     *         a negative value is given, the default value is used.
     *
     *         If a very short time (e.g. 0) is given, it is likely to happen either
     *         (1) that this client will fail to send a close frame to the server
     *         (in this case, you will probably see an error message "Flushing frames
     *         to the server failed: Socket closed") or (2) that the WebSocket
     *         connection will be closed before this client receives a close frame
     *         from the server (in this case, the second argument of {@link
     *         WebSocketListener#onDisconnected(WebSocket, WebSocketFrame,
     *         WebSocketFrame, boolean) WebSocketListener.onDisconnected} will be
     *         {@code null}).
     *
     * @return
     *         {@code this} object.
     *
     * @see WebSocketCloseCode
     *
     * @see <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1">RFC 6455, 5.5.1. Close</a>
     *
     * @since 1.26
     */
    public WebSocket disconnect(int closeCode, String reason, long closeDelay)
    {
        synchronized (mStateManager)
        {
            switch (mStateManager.getState())
            {
                case CREATED:
                    finishAsynchronously();
                    return this;

                case OPEN:
                    break;

                default:
                    // - CONNECTING
                    //     It won't happen unless the programmer dare call
                    //     open() and disconnect() in parallel.
                    //
                    // - CLOSING
                    //     A closing handshake has already been started.
                    //
                    // - CLOSED
                    //     The connection has already been closed.
                    return this;
            }

            // Change the state to CLOSING.
            mStateManager.changeToClosing(CloseInitiator.CLIENT);

            // Create a close frame.
            WebSocketFrame frame = WebSocketFrame.createCloseFrame(closeCode, reason);

            // Send the close frame to the server.
            sendFrame(frame);
        }

        // Notify the listeners of the state change.
        mListenerManager.callOnStateChanged(CLOSING);

        // If a negative value is given.
        if (closeDelay < 0)
        {
            // Use the default value.
            closeDelay = DEFAULT_CLOSE_DELAY;
        }

        // Request the threads to stop.
        stopThreads(closeDelay);

        return this;
    }


    /**
     * Get the agreed extensions.
     *
     * <p>
     * This method works correctly only after {@link #connect()} succeeds
     * (= after the opening handshake succeeds).
     * </p>
     *
     * @return
     *         The agreed extensions.
     */
    public List<WebSocketExtension> getAgreedExtensions()
    {
        return mAgreedExtensions;
    }


    /**
     * Get the agreed protocol.
     *
     * <p>
     * This method works correctly only after {@link #connect()} succeeds
     * (= after the opening handshake succeeds).
     * </p>
     *
     * @return
     *         The agreed protocol.
     */
    public String getAgreedProtocol()
    {
        return mAgreedProtocol;
    }


    /**
     * Send a WebSocket frame to the server.
     *
     * <p>
     * This method just queues the given frame. Actual transmission
     * is performed asynchronously.
     * </p>
     *
     * <p>
     * When the current state of this WebSocket is not {@link
     * WebSocketState#OPEN OPEN}, this method does not accept
     * the frame.
     * </p>
     *
     * <p>
     * Sending a <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1"
     * >close frame</a> changes the state to {@link WebSocketState#CLOSING
     * CLOSING} (if the current state is neither {@link WebSocketState#CLOSING
     * CLOSING} nor {@link WebSocketState#CLOSED CLOSED}).
     * </p>
     *
     * <p>
     * Note that the validity of the give frame is not checked.
     * For example, even if the payload length of a given frame
     * is greater than 125 and the opcode indicates that the
     * frame is a control frame, this method accepts the given
     * frame.
     * </p>
     *
     * @param frame
     *         A WebSocket frame to be sent to the server.
     *         If {@code null} is given, nothing is done.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendFrame(WebSocketFrame frame)
    {
        if (frame == null)
        {
            return this;
        }

        synchronized (mStateManager)
        {
            WebSocketState state = mStateManager.getState();

            if (state != OPEN && state != CLOSING)
            {
                return this;
            }
        }

        // The current state is either OPEN or CLOSING. Or, CLOSED.

        // Get the reference to the writing thread.
        WritingThread wt = mWritingThread;

        // Some applications call sendFrame() without waiting for the
        // notification of WebSocketListener.onConnected() (Issue #23),
        // and/or even after the connection is closed. That is, there
        // are chances that sendFrame() is called when mWritingThread
        // is null. So, it should be checked whether an instance of
        // WritingThread is available or not before calling queueFrame().
        if (wt == null)
        {
            // An instance of WritingThread is not available.
            return this;
        }

        // Split the frame into multiple frames if necessary.
        List<WebSocketFrame> frames = splitIfNecessary(frame);

        // Queue the frame or the frames. Even if the current state is
        // CLOSED, queueing won't be a big issue.

        // If the frame was not split.
        if (frames == null)
        {
            // Queue the frame.
            wt.queueFrame(frame);
        }
        else
        {
            for (WebSocketFrame f : frames)
            {
                // Queue the frame.
                wt.queueFrame(f);
            }
        }

        return this;
    }


    private List<WebSocketFrame> splitIfNecessary(WebSocketFrame frame)
    {
        return WebSocketFrame.splitIfNecessary(frame, mMaxPayloadSize, mPerMessageCompressionExtension);
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame()
     * createContinuationFrame()}{@code )}.
     * </p>
     *
     * <p>
     * Note that the FIN bit of a frame sent by this method is {@code false}.
     * If you want to set the FIN bit, use {@link #sendContinuation(boolean)
     * sendContinuation(boolean fin)} with {@code fin=true}.
     * </p>
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation()
    {
        return sendFrame(WebSocketFrame.createContinuationFrame());
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame()
     * createContinuationFrame()}{@code .}{@link
     * WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
     * </p>
     *
     * @param fin
     *         The FIN bit value.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation(boolean fin)
    {
        return sendFrame(WebSocketFrame.createContinuationFrame().setFin(fin));
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame(String)
     * createContinuationFrame}{@code (payload))}.
     * </p>
     *
     * <p>
     * Note that the FIN bit of a frame sent by this method is {@code false}.
     * If you want to set the FIN bit, use {@link #sendContinuation(String,
     * boolean) sendContinuation(String payload, boolean fin)} with {@code
     * fin=true}.
     * </p>
     *
     * @param payload
     *         The payload of a continuation frame.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation(String payload)
    {
        return sendFrame(WebSocketFrame.createContinuationFrame(payload));
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame(String)
     * createContinuationFrame}{@code (payload).}{@link
     * WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
     * </p>
     *
     * @param payload
     *         The payload of a continuation frame.
     *
     * @param fin
     *         The FIN bit value.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation(String payload, boolean fin)
    {
        return sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin));
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame(byte[])
     * createContinuationFrame}{@code (payload))}.
     * </p>
     *
     * <p>
     * Note that the FIN bit of a frame sent by this method is {@code false}.
     * If you want to set the FIN bit, use {@link #sendContinuation(byte[],
     * boolean) sendContinuation(byte[] payload, boolean fin)} with {@code
     * fin=true}.
     * </p>
     *
     * @param payload
     *         The payload of a continuation frame.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation(byte[] payload)
    {
        return sendFrame(WebSocketFrame.createContinuationFrame(payload));
    }


    /**
     * Send a continuation frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createContinuationFrame(byte[])
     * createContinuationFrame}{@code (payload).}{@link
     * WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
     * </p>
     *
     * @param payload
     *         The payload of a continuation frame.
     *
     * @param fin
     *         The FIN bit value.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendContinuation(byte[] payload, boolean fin)
    {
        return sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin));
    }


    /**
     * Send a text message to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createTextFrame(String)
     * createTextFrame}{@code (message))}.
     * </p>
     *
     * <p>
     * If you want to send a text frame that is to be followed by
     * continuation frames, use {@link #sendText(String, boolean)
     * setText(String payload, boolean fin)} with {@code fin=false}.
     * </p>
     *
     * @param message
     *         A text message to be sent to the server.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendText(String message)
    {
        return sendFrame(WebSocketFrame.createTextFrame(message));
    }


    /**
     * Send a text frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createTextFrame(String)
     * createTextFrame}{@code (payload).}{@link
     * WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
     * </p>
     *
     * @param payload
     *         The payload of a text frame.
     *
     * @param fin
     *         The FIN bit value.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendText(String payload, boolean fin)
    {
        return sendFrame(WebSocketFrame.createTextFrame(payload).setFin(fin));
    }


    /**
     * Send a binary message to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createBinaryFrame(byte[])
     * createBinaryFrame}{@code (message))}.
     * </p>
     *
     * <p>
     * If you want to send a binary frame that is to be followed by
     * continuation frames, use {@link #sendBinary(byte[], boolean)
     * setBinary(byte[] payload, boolean fin)} with {@code fin=false}.
     * </p>
     *
     * @param message
     *         A binary message to be sent to the server.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendBinary(byte[] message)
    {
        return sendFrame(WebSocketFrame.createBinaryFrame(message));
    }


    /**
     * Send a binary frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createBinaryFrame(byte[])
     * createBinaryFrame}{@code (payload).}{@link
     * WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
     * </p>
     *
     * @param payload
     *         The payload of a binary frame.
     *
     * @param fin
     *         The FIN bit value.
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendBinary(byte[] payload, boolean fin)
    {
        return sendFrame(WebSocketFrame.createBinaryFrame(payload).setFin(fin));
    }


    /**
     * Send a close frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createCloseFrame() createCloseFrame()}).
     * </p>
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendClose()
    {
        return sendFrame(WebSocketFrame.createCloseFrame());
    }


    /**
     * Send a close frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createCloseFrame(int)
     * createCloseFrame}{@code (closeCode))}.
     * </p>
     *
     * @param closeCode
     *         The close code.
     *
     * @return
     *         {@code this} object.
     *
     * @see WebSocketCloseCode
     */
    public WebSocket sendClose(int closeCode)
    {
        return sendFrame(WebSocketFrame.createCloseFrame(closeCode));
    }


    /**
     * Send a close frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createCloseFrame(int, String)
     * createCloseFrame}{@code (closeCode, reason))}.
     * </p>
     *
     * @param closeCode
     *         The close code.
     *
     * @param reason
     *         The close reason.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         {@code this} object.
     *
     * @see WebSocketCloseCode
     */
    public WebSocket sendClose(int closeCode, String reason)
    {
        return sendFrame(WebSocketFrame.createCloseFrame(closeCode, reason));
    }


    /**
     * Send a ping frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPingFrame() createPingFrame()}).
     * </p>
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPing()
    {
        return sendFrame(WebSocketFrame.createPingFrame());
    }


    /**
     * Send a ping frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPingFrame(byte[])
     * createPingFrame}{@code (payload))}.
     * </p>
     *
     * @param payload
     *         The payload for a ping frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPing(byte[] payload)
    {
        return sendFrame(WebSocketFrame.createPingFrame(payload));
    }


    /**
     * Send a ping frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPingFrame(String)
     * createPingFrame}{@code (payload))}.
     * </p>
     *
     * @param payload
     *         The payload for a ping frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPing(String payload)
    {
        return sendFrame(WebSocketFrame.createPingFrame(payload));
    }


    /**
     * Send a pong frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPongFrame() createPongFrame()}).
     * </p>
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPong()
    {
        return sendFrame(WebSocketFrame.createPongFrame());
    }


    /**
     * Send a pong frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPongFrame(byte[])
     * createPongFrame}{@code (payload))}.
     * </p>
     *
     * @param payload
     *         The payload for a pong frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPong(byte[] payload)
    {
        return sendFrame(WebSocketFrame.createPongFrame(payload));
    }


    /**
     * Send a pong frame to the server.
     *
     * <p>
     * This method is an alias of {@link #sendFrame(WebSocketFrame)
     * sendFrame}{@code (WebSocketFrame.}{@link
     * WebSocketFrame#createPongFrame(String)
     * createPongFrame}{@code (payload))}.
     * </p>
     *
     * @param payload
     *         The payload for a pong frame.
     *         Note that a control frame's payload length must be 125 bytes or less
     *         (RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
     *         >5.5. Control Frames</a>).
     *
     * @return
     *         {@code this} object.
     */
    public WebSocket sendPong(String payload)
    {
        return sendFrame(WebSocketFrame.createPongFrame(payload));
    }


    private void changeStateOnConnect() throws WebSocketException
    {
        synchronized (mStateManager)
        {
            // If the current state is not CREATED.
            if (mStateManager.getState() != CREATED)
            {
                throw new WebSocketException(
                    WebSocketError.NOT_IN_CREATED_STATE,
                    "The current state of the WebSocket is not CREATED.");
            }

            // Change the state to CONNECTING.
            mStateManager.setState(CONNECTING);
        }

        // Notify the listeners of the state change.
        mListenerManager.callOnStateChanged(CONNECTING);
    }


    /**
     * Perform the opening handshake.
     */
    private Map<String, List<String>> shakeHands(Socket socket) throws WebSocketException
    {
        // Get the input stream of the socket.
        WebSocketInputStream input = openInputStream(socket);

        // Get the output stream of the socket.
        WebSocketOutputStream output = openOutputStream(socket);

        // Generate a value for Sec-WebSocket-Key.
        String key = generateWebSocketKey();

        // Send an opening handshake to the server.
        writeHandshake(output, key);

        // Read the response from the server.
        Map<String, List<String>> headers = readHandshake(input, key);

        // Keep the input stream and the output stream to pass them
        // to the reading thread and the writing thread later.
        mInput  = input;
        mOutput = output;

        // The handshake succeeded.
        return headers;
    }


    /**
     * Open the input stream of the WebSocket connection.
     * The stream is used by the reading thread.
     */
    private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
    {
        try
        {
            // Get the input stream of the raw socket through which
            // this client receives data from the server.
            return new WebSocketInputStream(
                new BufferedInputStream(socket.getInputStream()));
        }
        catch (IOException e)
        {
            // Failed to get the input stream of the raw socket.
            throw new WebSocketException(
                WebSocketError.SOCKET_INPUT_STREAM_FAILURE,
                "Failed to get the input stream of the raw socket: " + e.getMessage(), e);
        }
    }


    /**
     * Open the output stream of the WebSocket connection.
     * The stream is used by the writing thread.
     */
    private WebSocketOutputStream openOutputStream(Socket socket) throws WebSocketException
    {
        try
        {
            // Get the output stream of the socket through which
            // this client sends data to the server.
            return new WebSocketOutputStream(
                new BufferedOutputStream(socket.getOutputStream()));
        }
        catch (IOException e)
        {
            // Failed to get the output stream from the raw socket.
            throw new WebSocketException(
                WebSocketError.SOCKET_OUTPUT_STREAM_FAILURE,
                "Failed to get the output stream from the raw socket: " + e.getMessage(), e);
        }
    }


    /**
     * Generate a value for Sec-WebSocket-Key.
     *
     * <blockquote>
     * <p><i>
     * The request MUST include a header field with the name Sec-WebSocket-Key.
     * The value of this header field MUST be a nonce consisting of a randomly
     * selected 16-byte value that has been base64-encoded (see Section 4 of
     * RFC 4648). The nonce MUST be selected randomly for each connection.
     * </i></p>
     * </blockquote>
     *
     * @return
     *         A randomly generated WebSocket key.
     */
    private static String generateWebSocketKey()
    {
        // "16-byte value"
        byte[] data = new byte[16];

        // "randomly selected"
        Misc.nextBytes(data);

        // "base64-encoded"
        return Base64.encode(data);
    }


    /**
     * Send an opening handshake request to the WebSocket server.
     */
    private void writeHandshake(WebSocketOutputStream output, String key) throws WebSocketException
    {
        // Generate an opening handshake sent to the server from this client.
        mHandshakeBuilder.setKey(key);
        String requestLine     = mHandshakeBuilder.buildRequestLine();
        List<String[]> headers = mHandshakeBuilder.buildHeaders();
        String handshake       = HandshakeBuilder.build(requestLine, headers);

        // Call onSendingHandshake() method of listeners.
        mListenerManager.callOnSendingHandshake(requestLine, headers);

        try
        {
            // Send the opening handshake to the server.
            output.write(handshake);
            output.flush();
        }
        catch (IOException e)
        {
            // Failed to send an opening handshake request to the server.
            throw new WebSocketException(
                WebSocketError.OPENING_HAHDSHAKE_REQUEST_FAILURE,
                "Failed to send an opening handshake request to the server: " + e.getMessage(), e);
        }
    }


    /**
     * Receive an opening handshake response from the WebSocket server.
     */
    private Map<String, List<String>> readHandshake(WebSocketInputStream input, String key) throws WebSocketException
    {
        return new HandshakeReader(this).readHandshake(input, key);
    }


    /**
     * Start both the reading thread and the writing thread.
     *
     * <p>
     * The reading thread will call {@link #onReadingThreadStarted()}
     * as its first step. Likewise, the writing thread will call
     * {@link #onWritingThreadStarted()} as its first step. After
     * both the threads have started, {@link #onThreadsStarted()} is
     * called.
     * </p>
     */
    private void startThreads()
    {
        ReadingThread readingThread = new ReadingThread(this);
        WritingThread writingThread = new WritingThread(this);

        synchronized (mThreadsLock)
        {
            mReadingThread = readingThread;
            mWritingThread = writingThread;
        }

        // Execute onThreadCreated of the listeners.
        readingThread.callOnThreadCreated();
        writingThread.callOnThreadCreated();

        readingThread.start();
        writingThread.start();
    }


    /**
     * Stop both the reading thread and the writing thread.
     *
     * <p>
     * The reading thread will call {@link #onReadingThreadFinished(WebSocketFrame)}
     * as its last step. Likewise, the writing thread will call {@link
     * #onWritingThreadFinished(WebSocketFrame)} as its last step.
     * After both the threads have stopped, {@link #onThreadsFinished()}
     * is called.
     * </p>
     */
    private void stopThreads(long closeDelay)
    {
        ReadingThread readingThread;
        WritingThread writingThread;

        synchronized (mThreadsLock)
        {
            readingThread = mReadingThread;
            writingThread = mWritingThread;

            mReadingThread = null;
            mWritingThread = null;
        }

        if (readingThread != null)
        {
            readingThread.requestStop(closeDelay);
        }

        if (writingThread != null)
        {
            writingThread.requestStop();
        }
    }


    /**
     * Get the input stream of the WebSocket connection.
     */
    WebSocketInputStream getInput()
    {
        return mInput;
    }


    /**
     * Get the output stream of the WebSocket connection.
     */
    WebSocketOutputStream getOutput()
    {
        return mOutput;
    }


    /**
     * Get the manager that manages the state of this {@code WebSocket} instance.
     */
    StateManager getStateManager()
    {
        return mStateManager;
    }


    /**
     * Get the manager that manages registered listeners.
     */
    ListenerManager getListenerManager()
    {
        return mListenerManager;
    }


    /**
     * Get the handshake builder. {@link HandshakeReader} uses this method.
     */
    HandshakeBuilder getHandshakeBuilder()
    {
        return mHandshakeBuilder;
    }


    /**
     * Set the agreed extensions. {@link HandshakeReader} uses this method.
     */
    void setAgreedExtensions(List<WebSocketExtension> extensions)
    {
        mAgreedExtensions = extensions;
    }


    /**
     * Set the agreed protocol. {@link HandshakeReader} uses this method.
     */
    void setAgreedProtocol(String protocol)
    {
        mAgreedProtocol = protocol;
    }


    /**
     * Called by the reading thread as its first step.
     */
    void onReadingThreadStarted()
    {
        boolean bothStarted = false;

        synchronized (mThreadsLock)
        {
            mReadingThreadStarted = true;

            if (mWritingThreadStarted)
            {
                // Both the reading thread and the writing thread have started.
                bothStarted = true;
            }
        }

        // Call onConnected() method of listeners if not called yet.
        callOnConnectedIfNotYet();

        // If both the reading thread and the writing thread have started.
        if (bothStarted)
        {
            onThreadsStarted();
        }
    }


    /**
     * Called by the writing thread as its first step.
     */
    void onWritingThreadStarted()
    {
        boolean bothStarted = false;

        synchronized (mThreadsLock)
        {
            mWritingThreadStarted = true;

            if (mReadingThreadStarted)
            {
                // Both the reading thread and the writing thread have started.
                bothStarted = true;
            }
        }

        // Call onConnected() method of listeners if not called yet.
        callOnConnectedIfNotYet();

        // If both the reading thread and the writing thread have started.
        if (bothStarted)
        {
            onThreadsStarted();
        }
    }


    /**
     * Call {@link WebSocketListener#onConnected(WebSocket, Map)} method
     * of the registered listeners if it has not been called yet. Either
     * the reading thread or the writing thread calls this method.
     */
    private void callOnConnectedIfNotYet()
    {
        synchronized (mOnConnectedCalledLock)
        {
            // If onConnected() has already been called.
            if (mOnConnectedCalled)
            {
                // Do not call onConnected() twice.
                return;
            }

            mOnConnectedCalled = true;
        }

        // Notify the listeners that the handshake succeeded.
        mListenerManager.callOnConnected(mServerHeaders);
    }


    /**
     * Called when both the reading thread and the writing thread have started.
     * This method is called in the context of either the reading thread or
     * the writing thread.
     */
    private void onThreadsStarted()
    {
        // Start sending ping frames periodically.
        // If the interval is zero, this call does nothing.
        mPingSender.start();

        // Likewise, start the pong sender.
        mPongSender.start();
    }


    /**
     * Called by the reading thread as its last step.
     */
    void onReadingThreadFinished(WebSocketFrame closeFrame)
    {
        synchronized (mThreadsLock)
        {
            mReadingThreadFinished = true;
            mServerCloseFrame = closeFrame;

            if (mWritingThreadFinished == false)
            {
                // Wait for the writing thread to finish.
                return;
            }
        }

        // Both the reading thread and the writing thread have finished.
        onThreadsFinished();
    }


    /**
     * Called by the writing thread as its last step.
     */
    void onWritingThreadFinished(WebSocketFrame closeFrame)
    {
        synchronized (mThreadsLock)
        {
            mWritingThreadFinished = true;
            mClientCloseFrame = closeFrame;

            if (mReadingThreadFinished == false)
            {
                // Wait for the reading thread to finish.
                return;
            }
        }

        // Both the reading thread and the writing thread have finished.
        onThreadsFinished();
    }


    /**
     * Called when both the reading thread and the writing thread have finished.
     * This method is called in the context of either the reading thread or
     * the writing thread.
     */
    private void onThreadsFinished()
    {
        finish();
    }


    void finish()
    {
        // Stop the ping sender and the pong sender.
        mPingSender.stop();
        mPongSender.stop();

        // Close the raw socket.
        Socket socket = mSocketConnector.getSocket();
        if (socket != null)
        {
            try
            {
                socket.close();
            }
            catch (Throwable t)
            {
                // Ignore any error raised by close().
            }
        }

        synchronized (mStateManager)
        {
            // Change the state to CLOSED.
            mStateManager.setState(CLOSED);
        }

        // Notify the listeners of the state change.
        mListenerManager.callOnStateChanged(CLOSED);

        // Notify the listeners that the WebSocket was disconnected.
        mListenerManager.callOnDisconnected(
            mServerCloseFrame, mClientCloseFrame, mStateManager.getClosedByServer());
    }


    /**
     * Call {@link #finish()} from within a separate thread.
     */
    private void finishAsynchronously()
    {
        WebSocketThread thread = new FinishThread(this);

        // Execute onThreadCreated() of the listeners.
        thread.callOnThreadCreated();

        thread.start();
    }


    /**
     * Find a per-message compression extension from among the agreed extensions.
     */
    private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension()
    {
        if (mAgreedExtensions == null)
        {
            return null;
        }

        for (WebSocketExtension extension : mAgreedExtensions)
        {
            if (extension instanceof PerMessageCompressionExtension)
            {
                return (PerMessageCompressionExtension)extension;
            }
        }

        return null;
    }


    /**
     * Get the PerMessageCompressionExtension in the agreed extensions.
     * This method returns null if a per-message compression extension
     * is not found in the agreed extensions.
     */
    PerMessageCompressionExtension getPerMessageCompressionExtension()
    {
        return mPerMessageCompressionExtension;
    }
}