File: python-socketio.1

package info (click to toggle)
python-socketio 5.13.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,148 kB
  • sloc: python: 11,546; makefile: 13; sh: 7
file content (2798 lines) | stat: -rw-r--r-- 80,800 bytes parent folder | download
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
'\" t
.\" Man page generated from reStructuredText.
.
.
.nr rst2man-indent-level 0
.
.de1 rstReportMargin
\\$1 \\n[an-margin]
level \\n[rst2man-indent-level]
level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
-
\\n[rst2man-indent0]
\\n[rst2man-indent1]
\\n[rst2man-indent2]
..
.de1 INDENT
.\" .rstReportMargin pre:
. RS \\$1
. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
. nr rst2man-indent-level +1
.\" .rstReportMargin post:
..
.de UNINDENT
. RE
.\" indent \\n[an-margin]
.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
.nr rst2man-indent-level -1
.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
..
.TH "PYTHON-SOCKETIO" "1" "May 19, 2025" "" "python-socketio"
.SH NAME
python-socketio \- python-socketio Documentation
.sp
This projects implements Socket.IO clients and servers that can run standalone
or integrated with a variety of Python web frameworks.
.SH GETTING STARTED
.SS What is Socket.IO?
.sp
Socket.IO is a transport protocol that enables real\-time bidirectional
event\-based communication between clients (typically, though not always,
web browsers) and a server. The official implementations of the client
and server components are written in JavaScript. This package provides
Python implementations of both, each with standard and asyncio variants.
.SS Version compatibility
.sp
The Socket.IO protocol has been through a number of revisions, and some of these
introduced backward incompatible changes, which means that the client and the
server must use compatible versions for everything to work.
.sp
If you are using the Python client and server, the easiest way to ensure compatibility
is to use the same version of this package for the client and the server. If you are
using this package with a different client or server, then you must ensure the
versions are compatible.
.sp
The version compatibility chart below maps versions of this package to versions
of the JavaScript reference implementation and the versions of the Socket.IO and
Engine.IO protocols.
.TS
box center;
l|l|l|l|l.
T{
JavaScript Socket.IO version
T}	T{
Socket.IO protocol revision
T}	T{
Engine.IO protocol revision
T}	T{
python\-socketio version
T}	T{
python\-engineio version
T}
_
T{
0.9.x
T}	T{
1, 2
T}	T{
1, 2
T}	T{
Not supported
T}	T{
Not supported
T}
_
T{
1.x and 2.x
T}	T{
3, 4
T}	T{
3
T}	T{
4.x
T}	T{
3.x
T}
_
T{
3.x and 4.x
T}	T{
5
T}	T{
4
T}	T{
5.x
T}	T{
4.x
T}
.TE
.SS Client Examples
.sp
The example that follows shows a simple Python client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

sio = socketio.Client()

@sio.event
def connect():
    print(\(aqconnection established\(aq)

@sio.event
def my_message(data):
    print(\(aqmessage received with \(aq, data)
    sio.emit(\(aqmy response\(aq, {\(aqresponse\(aq: \(aqmy response\(aq})

@sio.event
def disconnect():
    print(\(aqdisconnected from server\(aq)

sio.connect(\(aqhttp://localhost:5000\(aq)
sio.wait()
.EE
.UNINDENT
.UNINDENT
.sp
Below is a similar client, coded for \fBasyncio\fP (Python 3.5+ only):
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import asyncio
import socketio

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print(\(aqconnection established\(aq)

@sio.event
async def my_message(data):
    print(\(aqmessage received with \(aq, data)
    await sio.emit(\(aqmy response\(aq, {\(aqresponse\(aq: \(aqmy response\(aq})

@sio.event
async def disconnect():
    print(\(aqdisconnected from server\(aq)

async def main():
    await sio.connect(\(aqhttp://localhost:5000\(aq)
    await sio.wait()

if __name__ == \(aq__main__\(aq:
    asyncio.run(main())
.EE
.UNINDENT
.UNINDENT
.SS Client Features
.INDENT 0.0
.IP \(bu 2
Can connect to other Socket.IO servers that are compatible with the
JavaScript Socket.IO reference server.
.IP \(bu 2
Compatible with Python 3.8+.
.IP \(bu 2
Two versions of the client, one for standard Python and another for
asyncio.
.IP \(bu 2
Uses an event\-based architecture implemented with decorators that
hides the details of the protocol.
.IP \(bu 2
Implements HTTP long\-polling and WebSocket transports.
.IP \(bu 2
Automatically reconnects to the server if the connection is dropped.
.UNINDENT
.SS Server Examples
.sp
The following application is a basic server example that uses the Eventlet
asynchronous server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import eventlet
import socketio

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    \(aq/\(aq: {\(aqcontent_type\(aq: \(aqtext/html\(aq, \(aqfilename\(aq: \(aqindex.html\(aq}
})

@sio.event
def connect(sid, environ):
    print(\(aqconnect \(aq, sid)

@sio.event
def my_message(sid, data):
    print(\(aqmessage \(aq, data)

@sio.event
def disconnect(sid):
    print(\(aqdisconnect \(aq, sid)

if __name__ == \(aq__main__\(aq:
    eventlet.wsgi.server(eventlet.listen((\(aq\(aq, 5000)), app)
.EE
.UNINDENT
.UNINDENT
.sp
Below is a similar application, coded for \fBasyncio\fP (Python 3.5+ only) and the
Uvicorn web server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from aiohttp import web
import socketio

sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)

async def index(request):
    \(dq\(dq\(dqServe the client\-side application.\(dq\(dq\(dq
    with open(\(aqindex.html\(aq) as f:
        return web.Response(text=f.read(), content_type=\(aqtext/html\(aq)

@sio.event
def connect(sid, environ):
    print(\(dqconnect \(dq, sid)

@sio.event
async def chat_message(sid, data):
    print(\(dqmessage \(dq, data)

@sio.event
def disconnect(sid):
    print(\(aqdisconnect \(aq, sid)

app.router.add_static(\(aq/static\(aq, \(aqstatic\(aq)
app.router.add_get(\(aq/\(aq, index)

if __name__ == \(aq__main__\(aq:
    web.run_app(app)
.EE
.UNINDENT
.UNINDENT
.SS Server Features
.INDENT 0.0
.IP \(bu 2
Can connect to servers running other Socket.IO clients that are compatible
with the JavaScript reference client.
.IP \(bu 2
Compatible with Python 3.8+.
.IP \(bu 2
Two versions of the server, one for standard Python and another for
asyncio.
.IP \(bu 2
Supports large number of clients even on modest hardware due to being
asynchronous.
.IP \(bu 2
Can be hosted on any \X'tty: link https://wsgi.readthedocs.io/en/latest/index.html'\fI\%WSGI\fP\X'tty: link' or
\X'tty: link https://asgi.readthedocs.io/en/latest/'\fI\%ASGI\fP\X'tty: link' web server including
\X'tty: link https://gunicorn.org/'\fI\%Gunicorn\fP\X'tty: link', \X'tty: link https://github.com/encode/uvicorn'\fI\%Uvicorn\fP\X'tty: link',
\X'tty: link http://eventlet.net/'\fI\%eventlet\fP\X'tty: link' and \X'tty: link http://www.gevent.org'\fI\%gevent\fP\X'tty: link'\&.
.IP \(bu 2
Can be integrated with WSGI applications written in frameworks such as Flask, Django,
etc.
.IP \(bu 2
Can be integrated with \X'tty: link http://aiohttp.readthedocs.io/'\fI\%aiohttp\fP\X'tty: link',
\X'tty: link https://fastapi.tiangolo.com/'\fI\%FastAPI\fP\X'tty: link', \X'tty: link http://sanic.readthedocs.io/'\fI\%sanic\fP\X'tty: link'
and \X'tty: link http://www.tornadoweb.org/'\fI\%tornado\fP\X'tty: link' \fBasyncio\fP applications.
.IP \(bu 2
Broadcasting of messages to all connected clients, or to subsets of them
assigned to \(dqrooms\(dq.
.IP \(bu 2
Optional support for multiple servers, connected through a messaging queue
such as Redis or RabbitMQ.
.IP \(bu 2
Send messages to clients from external processes, such as Celery workers or
auxiliary scripts.
.IP \(bu 2
Event\-based architecture implemented with decorators that hides the details
of the protocol.
.IP \(bu 2
Support for HTTP long\-polling and WebSocket transports.
.IP \(bu 2
Support for XHR2 and XHR browsers.
.IP \(bu 2
Support for text and binary messages.
.IP \(bu 2
Support for gzip and deflate HTTP compression.
.IP \(bu 2
Configurable CORS responses, to avoid cross\-origin problems with browsers.
.UNINDENT
.SH THE SOCKET.IO CLIENTS
.sp
This package contains two Socket.IO clients:
.INDENT 0.0
.IP \(bu 2
a \(dqsimple\(dq client, which provides a straightforward API that is sufficient
for most applications
.IP \(bu 2
an \(dqevent\-driven\(dq client, which provides access to all the features of the
Socket.IO protocol
.UNINDENT
.sp
Each of these clients comes in two variants: one for the standard Python
library, and another for asynchronous applications built with the \fBasyncio\fP
package.
.SS Installation
.sp
To install the standard Python client along with its dependencies, use the
following command:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install \(dqpython\-socketio[client]\(dq
.EE
.UNINDENT
.UNINDENT
.sp
If instead you plan on using the \fBasyncio\fP client, then use this:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install \(dqpython\-socketio[asyncio_client]\(dq
.EE
.UNINDENT
.UNINDENT
.SS Using the Simple Client
.sp
The advantage of the simple client is that it abstracts away the logic required
to maintain a Socket.IO connection. This client handles disconnections and
reconnections in a completely transparent way, without adding any complexity to
the application.
.SS Creating a Client Instance
.sp
The easiest way to create a Socket.IO client is to use the context manager
interface:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
with socketio.SimpleClient() as sio:
    # ... connect to a server and use the client
    # ... no need to manually disconnect!

# asyncio
async with socketio.AsyncSimpleClient() as sio:
    # ... connect to a server and use the client
    # ... no need to manually disconnect!
.EE
.UNINDENT
.UNINDENT
.sp
With this usage the context manager will ensure that the client is properly
disconnected before exiting the \fBwith\fP or \fBasync with\fP block.
.sp
If preferred, a client can be manually instantiated:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
sio = socketio.SimpleClient()

# asyncio
sio = socketio.AsyncSimpleClient()
.EE
.UNINDENT
.UNINDENT
.SS Connecting to a Server
.sp
The connection to a server is established by calling the \fBconnect()\fP
method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttp://localhost:5000\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
In the case of the \fBasyncio\fP client, the method is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.connect(\(aqhttp://localhost:5000\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
By default the client first connects to the server using the long\-polling
transport, and then attempts to upgrade the connection to use WebSocket. To
connect directly using WebSocket, use the \fBtransports\fP argument:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttp://localhost:5000\(aq, transports=[\(aqwebsocket\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
Upon connection, the server assigns the client a unique session identifier.
The application can find this identifier in the \fBsid\fP attribute:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
print(\(aqmy sid is\(aq, sio.sid)
.EE
.UNINDENT
.UNINDENT
.sp
The Socket.IO transport that is used in the connection can be obtained from the
\fBtransport\fP attribute:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
print(\(aqmy transport is\(aq, sio.transport)
.EE
.UNINDENT
.UNINDENT
.sp
The transport is given as a string, and can be either \fB\(aqwebsocket\(aq\fP or
\fB\(aqpolling\(aq\fP\&.
.SS TLS/SSL Support
.sp
The client supports TLS/SSL connections. To enable it, use a \fBhttps://\fP
connection URL:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Or when using \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The client verifies server certificates by default. Consult the documentation
for the event\-driven client for information on how to customize this behavior.
.SS Emitting Events
.sp
The client can emit an event to the server using the \fBemit()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.emit(\(aqmy message\(aq, {\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
Or in the case of \fBasyncio\fP, as a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.emit(\(aqmy message\(aq, {\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
The arguments provided to the method are the name of the event to emit and the
optional data that is passed on to the server. The data can be of type \fBstr\fP,
\fBbytes\fP, \fBdict\fP, \fBlist\fP or \fBtuple\fP\&. When sending a \fBlist\fP or a
\fBtuple\fP, the elements in it need to be of any allowed types except \fBtuple\fP\&.
When a tuple is used, the elements of the tuple will be passed as individual
arguments to the server\-side event handler function.
.SS Receiving Events
.sp
The client can wait for the server to emit an event with the \fBreceive()\fP
method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
event = sio.receive()
print(f\(aqreceived event: \(dq{event[0]}\(dq with arguments {event[1:]}\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
When using \fBasyncio\fP, this method needs to be awaited:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
event = await sio.receive()
print(f\(aqreceived event: \(dq{event[0]}\(dq with arguments {event[1:]}\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The return value of \fBreceive()\fP is a list. The first element of this list is
the event name, while the remaining elements are the arguments passed by the
server.
.sp
With the usage shown above, the \fBreceive()\fP method will return only when an
event is received from the server. An optional timeout in seconds can be passed
to prevent the client from waiting forever:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from socketio.exceptions import TimeoutError

try:
    event = sio.receive(timeout=5)
except TimeoutError:
    print(\(aqtimed out waiting for event\(aq)
else:
    print(\(aqreceived event:\(aq, event)
.EE
.UNINDENT
.UNINDENT
.sp
Or with \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from socketio.exceptions import TimeoutError

try:
    event = await sio.receive(timeout=5)
except TimeoutError:
    print(\(aqtimed out waiting for event\(aq)
else:
    print(\(aqreceived event:\(aq, event)
.EE
.UNINDENT
.UNINDENT
.SS Disconnecting from the Server
.sp
At any time the client can request to be disconnected from the server by
invoking the \fBdisconnect()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.disconnect()
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP client this is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.disconnect()
.EE
.UNINDENT
.UNINDENT
.SS Debugging and Troubleshooting
.sp
To help you debug issues, the client can be configured to output logs to the
terminal:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
sio = socketio.Client(logger=True, engineio_logger=True)

# asyncio
sio = socketio.AsyncClient(logger=True, engineio_logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument controls logging related to the Socket.IO protocol,
while \fBengineio_logger\fP controls logs that originate in the low\-level
Engine.IO transport. These arguments can be set to \fBTrue\fP to output logs to
\fBstderr\fP, or to an object compatible with Python\(aqs \fBlogging\fP package
where the logs should be emitted to. A value of \fBFalse\fP disables logging.
.sp
Logging can help identify the cause of connection problems, unexpected
disconnections and other issues.
.SS Using the Event\-Driven Client
.SS Creating a Client Instance
.sp
To instantiate an Socket.IO client, simply create an instance of the
appropriate client class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
sio = socketio.Client()

# asyncio
sio = socketio.AsyncClient()
.EE
.UNINDENT
.UNINDENT
.SS Defining Event Handlers
.sp
The Socket.IO protocol is event based. When a server wants to communicate with
a client it \fIemits\fP an event. Each event has a name, and a list of
arguments. The client registers event handler functions with the
\fBsocketio.Client.event()\fP or \fBsocketio.Client.on()\fP decorators:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def message(data):
    print(\(aqI received a message!\(aq)

@sio.on(\(aqmy message\(aq)
def on_message(data):
    print(\(aqI received a message!\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
In the first example the event name is obtained from the name of the
handler function. The second example is slightly more verbose, but it
allows the event name to be different than the function name or to include
characters that are illegal in function names, such as spaces.
.sp
For the \fBasyncio\fP client, event handlers can be regular functions as above,
or can also be coroutines:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
async def message(data):
    print(\(aqI received a message!\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
If the server includes arguments with an event, those are passed to the
handler function as arguments.
.SS Catch\-All Event and Namespace Handlers
.sp
A \(dqcatch\-all\(dq event handler is invoked for any events that do not have an
event handler. You can define a catch\-all handler using \fB\(aq*\(aq\fP as event name:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq)
def any_event(event, sid, data):
     pass
.EE
.UNINDENT
.UNINDENT
.sp
Asyncio servers can also use a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq)
async def any_event(event, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
A catch\-all event handler receives the event name as a first argument. The
remaining arguments are the same as for a regular event handler.
.sp
The \fBconnect\fP and \fBdisconnect\fP events have to be defined explicitly and are
not invoked on a catch\-all event handler.
.sp
Similarily, a \(dqcatch\-all\(dq namespace handler is invoked for any connected
namespaces that do not have an explicitly defined event handler. As with
catch\-all events, \fB\(aq*\(aq\fP is used in place of a namespace:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aqmy_event\(aq, namespace=\(aq*\(aq)
def my_event_any_namespace(namespace, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
For these events, the namespace is passed as first argument, followed by the
regular arguments of the event.
.sp
Lastly, it is also possible to define a \(dqcatch\-all\(dq handler for all events on
all namespaces:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq, namespace=\(aq*\(aq)
def any_event_any_namespace(event, namespace, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
Event handlers with catch\-all events and namespaces receive the event name and
the namespace as first and second arguments.
.SS Connect, Connect Error and Disconnect Event Handlers
.sp
The \fBconnect\fP, \fBconnect_error\fP and \fBdisconnect\fP events are special; they
are invoked automatically when a client connects or disconnects from the
server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def connect():
    print(\(dqI\(aqm connected!\(dq)

@sio.event
def connect_error(data):
    print(\(dqThe connection failed!\(dq)

@sio.event
def disconnect(reason):
    print(\(dqI\(aqm disconnected! reason:\(dq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBconnect_error\fP handler is invoked when a connection attempt fails. If
the server provides arguments, these are passed on to the handler. The server
can use an argument to provide information to the client regarding the
connection failure.
.sp
The \fBdisconnect\fP handler is invoked for application initiated disconnects,
server initiated disconnects, or accidental disconnects, for example due to
networking failures. In the case of an accidental disconnection, the client is
going to attempt to reconnect immediately after invoking the disconnect
handler. As soon as the connection is re\-established the connect handler will
be invoked once again. The handler receives a \fBreason\fP argument which
provides the cause of the disconnection:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def disconnect(reason):
    if reason == sio.reason.CLIENT_DISCONNECT:
        print(\(aqthe client disconnected\(aq)
    elif reason == sio.reason.SERVER_DISCONNECT:
        print(\(aqthe server disconnected the client\(aq)
    else:
        print(\(aqdisconnect reason:\(aq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
See the The \fBsocketio.Client.reason\fP attribute for a list of possible
disconnection reasons.
.sp
The \fBconnect\fP, \fBconnect_error\fP and \fBdisconnect\fP events have to be
defined explicitly and are not invoked on a catch\-all event handler.
.SS Connecting to a Server
.sp
The connection to a server is established by calling the \fBconnect()\fP
method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttp://localhost:5000\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
In the case of the \fBasyncio\fP client, the method is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.connect(\(aqhttp://localhost:5000\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Upon connection, the server assigns the client a unique session identifier.
The application can find this identifier in the \fBsid\fP attribute:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
print(\(aqmy sid is\(aq, sio.sid)
.EE
.UNINDENT
.UNINDENT
.sp
The Socket.IO transport that is used in the connection can be obtained from the
\fBtransport\fP attribute:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
print(\(aqmy transport is\(aq, sio.transport)
.EE
.UNINDENT
.UNINDENT
.sp
The transport is given as a string, and can be either \fB\(aqwebsocket\(aq\fP or
\fB\(aqpolling\(aq\fP\&.
.SS TLS/SSL Support
.sp
The client supports TLS/SSL connections. To enable it, use a \fBhttps://\fP
connection URL:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Or when using \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The client will verify the server certificate by default. To disable
certificate verification, or to use other less common options such as client
certificates, the client must be initialized with a custom HTTP session object
that is configured with the desired TLS/SSL options.
.sp
The following example disables server certificate verification, which can be
useful when connecting to a server that uses a self\-signed certificate:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
http_session = requests.Session()
http_session.verify = False
sio = socketio.Client(http_session=http_session)
sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
And when using \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
connector = aiohttp.TCPConnector(ssl=False)
http_session = aiohttp.ClientSession(connector=connector)
sio = socketio.AsyncClient(http_session=http_session)
await sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Instead of disabling certificate verification, you can provide a custom
certificate authority bundle to verify the certificate against:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
http_session = requests.Session()
http_session.verify = \(aq/path/to/ca.pem\(aq
sio = socketio.Client(http_session=http_session)
sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
And for \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(\(aq/path/to/ca.pem\(aq)
connector = aiohttp.TCPConnector(ssl=ssl_context)
http_session = aiohttp.ClientSession(connector=connector)
sio = socketio.AsyncClient(http_session=http_session)
await sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Below you can see how to use a client certificate to authenticate against the
server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
http_session = requests.Session()
http_session.cert = (\(aq/path/to/client/cert.pem\(aq, \(aq/path/to/client/key.pem\(aq)
sio = socketio.Client(http_session=http_session)
sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
And for \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(\(aq/path/to/client/cert.pem\(aq,
                            \(aq/path/to/client/key.pem\(aq)
connector = aiohttp.TCPConnector(ssl=ssl_context)
http_session = aiohttp.ClientSession(connector=connector)
sio = socketio.AsyncClient(http_session=http_session)
await sio.connect(\(aqhttps://example.com\(aq)
.EE
.UNINDENT
.UNINDENT
.SS Emitting Events
.sp
The client can emit an event to the server using the \fBemit()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.emit(\(aqmy message\(aq, {\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
Or in the case of \fBasyncio\fP, as a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.emit(\(aqmy message\(aq, {\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
The arguments provided to the method are the name of the event to emit and the
optional data that is passed on to the server. The data can be of type \fBstr\fP,
\fBbytes\fP, \fBdict\fP, \fBlist\fP or \fBtuple\fP\&. When sending a \fBlist\fP or a
\fBtuple\fP, the elements in it need to be of any allowed types except \fBtuple\fP\&.
When a tuple is used, the elements of the tuple will be passed as individual
arguments to the server\-side event handler function.
.sp
The \fBemit()\fP method can be invoked inside an event handler as a response
to a server event, or in any other part of the application, including in
background tasks.
.SS Event Callbacks
.sp
When a server emits an event to a client, it can optionally provide a
callback function, to be invoked as a way of acknowledgment that the server
has processed the event. While this is entirely managed by the server, the
client can provide a list of return values that are to be passed on to the
callback function set up by the server. This is achieved simply by returning
the desired values from the handler function:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def my_event(sid, data):
    # handle the message
    return \(dqOK\(dq, 123
.EE
.UNINDENT
.UNINDENT
.sp
Likewise, the client can request a callback function to be invoked after the
server has processed an event. The \fBsocketio.Server.emit()\fP method has an
optional \fBcallback\fP argument that can be set to a callable. If this
argument is given, the callable will be invoked after the server has processed
the event, and any values returned by the server handler will be passed as
arguments to this function.
.SS Namespaces
.sp
The Socket.IO protocol supports multiple logical connections, all multiplexed
on the same physical connection. Clients can open multiple connections by
specifying a different \fInamespace\fP on each. Namespaces use a path syntax
starting with a forward slash. A list of namespaces can be given by the client
in the \fBconnect()\fP call. For example, this example creates two logical
connections, the default one plus a second connection under the \fB/chat\fP
namespace:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.connect(\(aqhttp://localhost:5000\(aq, namespaces=[\(aq/chat\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
To define event handlers on a namespace, the \fBnamespace\fP argument must be
added to the corresponding decorator:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event(namespace=\(aq/chat\(aq)
def my_custom_event(sid, data):
    pass

@sio.on(\(aqconnect\(aq, namespace=\(aq/chat\(aq)
def on_connect():
    print(\(dqI\(aqm connected to the /chat namespace!\(dq)
.EE
.UNINDENT
.UNINDENT
.sp
Likewise, the client can emit an event to the server on a namespace by
providing its in the \fBemit()\fP call:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.emit(\(aqmy message\(aq, {\(aqfoo\(aq: \(aqbar\(aq}, namespace=\(aq/chat\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
If the \fBnamespaces\fP argument of the \fBconnect()\fP call isn\(aqt given, any
namespaces used in event handlers are automatically connected.
.SS Class\-Based Namespaces
.sp
As an alternative to the decorator\-based event handlers, the event handlers
that belong to a namespace can be created as methods of a subclass of
\fBsocketio.ClientNamespace\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
class MyCustomNamespace(socketio.ClientNamespace):
    def on_connect(self):
        pass

    def on_disconnect(self, reason):
        pass

    def on_my_event(self, data):
        self.emit(\(aqmy_response\(aq, data)

sio.register_namespace(MyCustomNamespace(\(aq/chat\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
For asyncio based servers, namespaces must inherit from
\fBsocketio.AsyncClientNamespace\fP, and can define event handlers as
coroutines if desired:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
class MyCustomNamespace(socketio.AsyncClientNamespace):
    def on_connect(self):
        pass

    def on_disconnect(self, reason):
        pass

    async def on_my_event(self, data):
        await self.emit(\(aqmy_response\(aq, data)

sio.register_namespace(MyCustomNamespace(\(aq/chat\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
A catch\-all class\-based namespace handler can be defined by passing \fB\(aq*\(aq\fP as
the namespace during registration:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.register_namespace(MyCustomNamespace(\(aq*\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
When class\-based namespaces are used, any events received by the client are
dispatched to a method named as the event name with the \fBon_\fP prefix. For
example, event \fBmy_event\fP will be handled by a method named \fBon_my_event\fP\&.
If an event is received for which there is no corresponding method defined in
the namespace class, then the event is ignored. All event names used in
class\-based namespaces must use characters that are legal in method names.
.sp
As a convenience to methods defined in a class\-based namespace, the namespace
instance includes versions of several of the methods in the
\fBsocketio.Client\fP and \fBsocketio.AsyncClient\fP classes that
default to the proper namespace when the \fBnamespace\fP argument is not given.
.sp
In the case that an event has a handler in a class\-based namespace, and also a
decorator\-based function handler, only the standalone function handler is
invoked.
.SS Disconnecting from the Server
.sp
At any time the client can request to be disconnected from the server by
invoking the \fBdisconnect()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.disconnect()
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP client this is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.disconnect()
.EE
.UNINDENT
.UNINDENT
.SS Managing Background Tasks
.sp
When a client connection to the server is established, a few background
tasks will be spawned to keep the connection alive and handle incoming
events. The application running on the main thread is free to do any
work, as this is not going to prevent the functioning of the Socket.IO
client.
.sp
If the application does not have anything to do in the main thread and
just wants to wait until the connection with the server ends, it can call
the \fBwait()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.wait()
.EE
.UNINDENT
.UNINDENT
.sp
Or in the \fBasyncio\fP version:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.wait()
.EE
.UNINDENT
.UNINDENT
.sp
For the convenience of the application, a helper function is provided to
start a custom background task:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
def my_background_task(my_argument):
    # do some background work here!
    pass

task = sio.start_background_task(my_background_task, 123)
.EE
.UNINDENT
.UNINDENT
.sp
The arguments passed to this method are the background function and any
positional or keyword arguments to invoke the function with.
.sp
Here is the \fBasyncio\fP version:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
async def my_background_task(my_argument):
    # do some background work here!
    pass

task = sio.start_background_task(my_background_task, 123)
.EE
.UNINDENT
.UNINDENT
.sp
Note that this function is not a coroutine, since it does not wait for the
background function to end. The background function must be a coroutine.
.sp
The \fBsleep()\fP method is a second convenience function that is provided for
the benefit of applications working with background tasks of their own:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.sleep(2)
.EE
.UNINDENT
.UNINDENT
.sp
Or for \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await sio.sleep(2)
.EE
.UNINDENT
.UNINDENT
.sp
The single argument passed to the method is the number of seconds to sleep
for.
.SS Debugging and Troubleshooting
.sp
To help you debug issues, the client can be configured to output logs to the
terminal:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
sio = socketio.Client(logger=True, engineio_logger=True)

# asyncio
sio = socketio.AsyncClient(logger=True, engineio_logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument controls logging related to the Socket.IO protocol,
while \fBengineio_logger\fP controls logs that originate in the low\-level
Engine.IO transport. These arguments can be set to \fBTrue\fP to output logs to
\fBstderr\fP, or to an object compatible with Python\(aqs \fBlogging\fP package
where the logs should be emitted to. A value of \fBFalse\fP disables logging.
.sp
Logging can help identify the cause of connection problems, unexpected
disconnections and other issues.
.SH THE SOCKET.IO SERVER
.sp
This package contains two Socket.IO servers:
.INDENT 0.0
.IP \(bu 2
The \fBsocketio.Server()\fP class creates a server compatible with the
Python standard library.
.IP \(bu 2
The \fBsocketio.AsyncServer()\fP class creates a server compatible with
the \fBasyncio\fP package.
.UNINDENT
.sp
The methods in the two servers are the same, with the only difference that in
the \fBasyncio\fP server most methods are implemented as coroutines.
.SS Installation
.sp
To install the Socket.IO server along with its dependencies, use the following
command:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install python\-socketio
.EE
.UNINDENT
.UNINDENT
.SS Creating a Server Instance
.sp
A Socket.IO server is an instance of class \fBsocketio.Server\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# create a Socket.IO server
sio = socketio.Server()
.EE
.UNINDENT
.UNINDENT
.sp
For asyncio based servers, the \fBsocketio.AsyncServer\fP class provides
the same functionality, but in a coroutine friendly format:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# create a Socket.IO server
sio = socketio.AsyncServer()
.EE
.UNINDENT
.UNINDENT
.SS Running the Server
.sp
To run the Socket.IO application it is necessary to configure a web server to
receive incoming requests from clients and forward them to the Socket.IO
server instance. To simplify this task, several integrations are available,
including support for the \X'tty: link https://wsgi.readthedocs.io/en/latest/what.html'\fI\%WSGI\fP\X'tty: link'
and \X'tty: link https://asgi.readthedocs.io/en/latest/'\fI\%ASGI\fP\X'tty: link' standards.
.SS Running as a WSGI Application
.sp
To configure the Socket.IO server as a WSGI application wrap the server
instance with the \fBsocketio.WSGIApp\fP class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# wrap with a WSGI application
app = socketio.WSGIApp(sio)
.EE
.UNINDENT
.UNINDENT
.sp
The resulting WSGI application can be executed with supported WSGI servers
such as \X'tty: link https://werkzeug.palletsprojects.com'\fI\%Werkzeug\fP\X'tty: link' for development and
\X'tty: link https://gunicorn.org/'\fI\%Gunicorn\fP\X'tty: link' for production.
.sp
When combining Socket.IO with a web application written with a WSGI framework
such as Flask or Django, the \fBWSGIApp\fP class can wrap both applications
together and route traffic to them:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from mywebapp import app  # a Flask, Django, etc. application
app = socketio.WSGIApp(sio, app)
.EE
.UNINDENT
.UNINDENT
.SS Running as an ASGI Application
.sp
To configure the Socket.IO server as an ASGI application wrap the server
instance with the \fBsocketio.ASGIApp\fP class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# wrap with ASGI application
app = socketio.ASGIApp(sio)
.EE
.UNINDENT
.UNINDENT
.sp
The resulting ASGI application can be executed with an ASGI compliant web
server, for example \X'tty: link https://www.uvicorn.org/'\fI\%Uvicorn\fP\X'tty: link'\&.
.sp
Socket.IO can also be combined with a web application written with an ASGI
web framework such as FastAPI. In that case, the \fBASGIApp\fP class can wrap
both applications together and route traffic to them:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from mywebapp import app  # a FastAPI or other ASGI application
app = socketio.ASGIApp(sio, app)
.EE
.UNINDENT
.UNINDENT
.SS Serving Static Files
.sp
The Socket.IO server can be configured to serve static files to clients. This
is particularly useful to deliver HTML, CSS and JavaScript files to clients
when this package is used without a companion web framework.
.sp
Static files are configured with a Python dictionary in which each key/value
pair is a static file mapping rule. In its simplest form, this dictionary has
one or more static file URLs as keys, and the corresponding files in the server
as values:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
static_files = {
    \(aq/\(aq: \(aqlatency.html\(aq,
    \(aq/static/socket.io.js\(aq: \(aqstatic/socket.io.js\(aq,
    \(aq/static/style.css\(aq: \(aqstatic/style.css\(aq,
}
.EE
.UNINDENT
.UNINDENT
.sp
With this example configuration, when the server receives a request for \fB/\fP
(the root URL) it will return the contents of the file \fBlatency.html\fP in the
current directory, and will assign a content type based on the file extension,
in this case \fBtext/html\fP\&.
.sp
Files with the \fB\&.html\fP, \fB\&.css\fP, \fB\&.js\fP, \fB\&.json\fP, \fB\&.jpg\fP, \fB\&.png\fP,
\fB\&.gif\fP and \fB\&.txt\fP file extensions are automatically recognized and
assigned the correct content type. For files with other file extensions or
with no file extension, the \fBapplication/octet\-stream\fP content type is used
as a default.
.sp
If desired, an explicit content type for a static file can be given as follows:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
static_files = {
    \(aq/\(aq: {\(aqfilename\(aq: \(aqlatency.html\(aq, \(aqcontent_type\(aq: \(aqtext/plain\(aq},
}
.EE
.UNINDENT
.UNINDENT
.sp
It is also possible to configure an entire directory in a single rule, so that
all the files in it are served as static files:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
static_files = {
    \(aq/static\(aq: \(aq./public\(aq,
}
.EE
.UNINDENT
.UNINDENT
.sp
In this example any files with URLs starting with \fB/static\fP will be served
directly from the \fBpublic\fP folder in the current directory, so for example,
the URL \fB/static/index.html\fP will return local file \fB\&./public/index.html\fP
and the URL \fB/static/css/styles.css\fP will return local file
\fB\&./public/css/styles.css\fP\&.
.sp
If a URL that ends in a \fB/\fP is requested, then a default filename of
\fBindex.html\fP is appended to it. In the previous example, a request for the
\fB/static/\fP URL would return local file \fB\&./public/index.html\fP\&. The default
filename to serve for slash\-ending URLs can be set in the static files
dictionary with an empty key:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
static_files = {
    \(aq/static\(aq: \(aq./public\(aq,
    \(aq\(aq: \(aqimage.gif\(aq,
}
.EE
.UNINDENT
.UNINDENT
.sp
With this configuration, a request for \fB/static/\fP would return
local file \fB\&./public/image.gif\fP\&. A non\-standard content type can also be
specified if needed:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
static_files = {
    \(aq/static\(aq: \(aq./public\(aq,
    \(aq\(aq: {\(aqfilename\(aq: \(aqimage.gif\(aq, \(aqcontent_type\(aq: \(aqtext/plain\(aq},
}
.EE
.UNINDENT
.UNINDENT
.sp
The static file configuration dictionary is given as the \fBstatic_files\fP
argument to the \fBsocketio.WSGIApp\fP or \fBsocketio.ASGIApp\fP classes:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# for standard WSGI applications
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files=static_files)

# for asyncio\-based ASGI applications
sio = socketio.AsyncServer()
app = socketio.ASGIApp(sio, static_files=static_files)
.EE
.UNINDENT
.UNINDENT
.sp
The routing precedence in these two classes is as follows:
.INDENT 0.0
.IP \(bu 2
First, the path is checked against the Socket.IO endpoint.
.IP \(bu 2
Next, the path is checked against the static file configuration, if present.
.IP \(bu 2
If the path did not match the Socket.IO endpoint or any static file, control
is passed to the secondary application if configured, else a 404 error is
returned.
.UNINDENT
.sp
Note: static file serving is intended for development use only, and as such
it lacks important features such as caching. Do not use in a production
environment.
.SS Events
.sp
The Socket.IO protocol is event based. When a client wants to communicate with
the server, or the server wants to communicate with one or more clients, they
\fIemit\fP an event to the other party. Each event has a name, and an optional list
of arguments.
.SS Listening to Events
.sp
To receive events from clients, the server application must register event
handler functions. These functions are invoked when the corresponding events
are emitted by clients. To register a handler for an event, the
\fBsocketio.Server.event()\fP or \fBsocketio.Server.on()\fP decorators are used:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def my_event(sid, data):
    pass

@sio.on(\(aqmy custom event\(aq)
def another_event(sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
In the first example the event name is obtained from the name of the handler
function. The second example is slightly more verbose, but it allows the event
name to be different than the function name or to include characters that are
illegal in function names, such as spaces.
.sp
For asyncio servers, event handlers can optionally be given as coroutines:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
async def my_event(sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
The \fBsid\fP argument that is passed to all handlers is the Socket.IO session
id, a unique identifier that Socket.IO assigns to each client connection. All
the events sent by a given client will have the same \fBsid\fP value.
.SS Connect and Disconnect Events
.sp
The \fBconnect\fP and \fBdisconnect\fP events are special; they are invoked
automatically when a client connects or disconnects from the server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def connect(sid, environ, auth):
    print(\(aqconnect \(aq, sid)

@sio.event
def disconnect(sid, reason):
    print(\(aqdisconnect \(aq, sid, reason)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBconnect\fP event is an ideal place to perform user authentication, and
any necessary mapping between user entities in the application and the \fBsid\fP
that was assigned to the client.
.sp
In addition to the \fBsid\fP, the connect handler receives \fBenviron\fP as an
argument, with the request information in standard WSGI format, including HTTP
headers. The connect handler also receives the \fBauth\fP argument with any
authentication details passed by the client, or \fBNone\fP if the client did not
pass any authentication.
.sp
After inspecting the arguments, the connect event handler can return \fBFalse\fP
to reject the connection with the client. Sometimes it is useful to pass data
back to the client being rejected. In that case instead of returning \fBFalse\fP
a \fBsocketio.exceptions.ConnectionRefusedError\fP exception can be raised,
and all of its arguments will be sent to the client with the rejection
message:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def connect(sid, environ, auth):
    raise ConnectionRefusedError(\(aqauthentication failed\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The disconnect handler receives the \fBsid\fP assigned to the client and a
\fBreason\fP, which provides the cause of the disconnection:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def disconnect(sid, reason):
    if reason == sio.reason.CLIENT_DISCONNECT:
        print(\(aqthe client disconnected\(aq)
    elif reason == sio.reason.SERVER_DISCONNECT:
        print(\(aqthe server disconnected the client\(aq)
    else:
        print(\(aqdisconnect reason:\(aq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
See the The \fBsocketio.Server.reason\fP attribute for a list of possible
disconnection reasons.
.SS Catch\-All Event Handlers
.sp
A \(dqcatch\-all\(dq event handler is invoked for any events that do not have an
event handler. You can define a catch\-all handler using \fB\(aq*\(aq\fP as event name:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq)
def any_event(event, sid, data):
     pass
.EE
.UNINDENT
.UNINDENT
.sp
Asyncio servers can also use a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq)
async def any_event(event, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
A catch\-all event handler receives the event name as a first argument. The
remaining arguments are the same as for a regular event handler.
.sp
Note that the \fBconnect\fP and \fBdisconnect\fP events have to be defined
explicitly and are not invoked on a catch\-all event handler.
.SS Emitting Events to Clients
.sp
Socket.IO is a bidirectional protocol, so at any time the server can send an
event to its connected clients. The \fBsocketio.Server.emit()\fP method is
used for this task:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.emit(\(aqmy event\(aq, {\(aqdata\(aq: \(aqfoobar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
The first argument is the event name, followed by an optional data payload of
type \fBstr\fP, \fBbytes\fP, \fBlist\fP, \fBdict\fP or \fBtuple\fP\&. When sending a
\fBlist\fP, \fBdict\fP or \fBtuple\fP, the elements are also constrained to the same
data types. When a \fBtuple\fP is sent, the elements of the tuple will be passed
as multiple arguments to the client\-side event handler function.
.sp
The above example will send the event to all the clients are connected.
Sometimes the server may want to send an event just to one particular client.
This can be achieved by adding a \fBto\fP argument to the emit call, with the
\fBsid\fP of the client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.emit(\(aqmy event\(aq, {\(aqdata\(aq: \(aqfoobar\(aq}, to=user_sid)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBto\fP argument is used to identify the client that should receive the
event, and is set to the \fBsid\fP value assigned to that client\(aqs connection
with the server. When \fBto\fP is omitted, the event is broadcasted to all
connected clients.
.SS Acknowledging Events
.sp
When a client sends an event to the server, it can optionally request to
receive acknowledgment from the server. The sending of acknowledgements is
automatically managed by the Socket.IO server, but the event handler function
can provide a list of values that are to be passed on to the client with the
acknowledgement simply by returning them:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def my_event(sid, data):
    # handle the message
    return \(dqOK\(dq, 123  # <\-\- client will have these as acknowledgement
.EE
.UNINDENT
.UNINDENT
.SS Requesting Client Acknowledgements
.sp
Similar to how clients can request acknowledgements from the server, when the
server is emitting to a single client it can also ask the client to acknowledge
the event, and optionally return one or more values as a response.
.sp
The Socket.IO server supports two ways of working with client acknowledgements.
The most convenient method is to replace \fBsocketio.Server.emit()\fP with
\fBsocketio.Server.call()\fP\&. The \fBcall()\fP method will emit the event, and
then wait until the client sends an acknowledgement, returning any values
provided by the client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
response = sio.call(\(aqmy event\(aq, {\(aqdata\(aq: \(aqfoobar\(aq}, to=user_sid)
.EE
.UNINDENT
.UNINDENT
.sp
A much more primitive acknowledgement solution uses callback functions. The
\fBsocketio.Server.emit()\fP method has an optional \fBcallback\fP argument that
can be set to a callable. If this argument is given, the callable will be
invoked after the client has processed the event, and any values returned by
the client will be passed as arguments to this function:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
def my_callback():
    print(\(dqcallback invoked!\(dq)

sio.emit(\(aqmy event\(aq, {\(aqdata\(aq: \(aqfoobar\(aq}, to=user_sid, callback=my_callback)
.EE
.UNINDENT
.UNINDENT
.SS Rooms
.sp
To make it easy for the server to emit events to groups of related clients,
the application can put its clients into \(dqrooms\(dq, and then address messages to
these rooms.
.sp
In previous examples, the \fBto\fP argument of the \fBsocketio.SocketIO.emit()\fP
method was used to designate a specific client as the recipient of the event.
The \fBto\fP argument can also be given the name of a room, and then all the
clients that are in that room will receive the event.
.sp
The application can create as many rooms as needed and manage which clients are
in them using the \fBsocketio.Server.enter_room()\fP and
\fBsocketio.Server.leave_room()\fP methods. Clients can be in as many
rooms as needed and can be moved between rooms when necessary.
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def begin_chat(sid):
    sio.enter_room(sid, \(aqchat_users\(aq)

@sio.event
def exit_chat(sid):
    sio.leave_room(sid, \(aqchat_users\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
In chat applications it is often desired that an event is broadcasted to all
the members of the room except one, which is the originator of the event such
as a chat message. The \fBsocketio.Server.emit()\fP method provides an
optional \fBskip_sid\fP argument to indicate a client that should be skipped
during the broadcast.
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def my_message(sid, data):
    sio.emit(\(aqmy reply\(aq, data, room=\(aqchat_users\(aq, skip_sid=sid)
.EE
.UNINDENT
.UNINDENT
.SS Namespaces
.sp
The Socket.IO protocol supports multiple logical connections, all multiplexed
on the same physical connection. Clients can open multiple connections by
specifying a different \fInamespace\fP on each. A namespace is given by the client
as a pathname following the hostname and port. For example, connecting to
\fIhttp://example.com:8000/chat\fP would open a connection to the namespace
\fI/chat\fP\&.
.sp
Each namespace works independently from the others, with separate session
IDs (\fBsid\fPs), event handlers and rooms. Namespaces can be defined directly
in the event handler functions, or they can also be created as classes.
.SS Decorator\-Based Namespaces
.sp
Decorator\-based namespaces are regular event handlers that include the
\fBnamespace\fP argument in their decorator:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event(namespace=\(aq/chat\(aq)
def my_custom_event(sid, data):
    pass

@sio.on(\(aqmy custom event\(aq, namespace=\(aq/chat\(aq)
def my_custom_event(sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
When emitting an event, the \fBnamespace\fP optional argument is used to specify
which namespace to send it on. When the \fBnamespace\fP argument is omitted, the
default Socket.IO namespace, which is named \fB/\fP, is used.
.sp
It is important that applications that use multiple namespaces specify the
correct namespace when setting up their event handlers and rooms using the
optional \fBnamespace\fP argument. This argument must also be specified when
emitting events under a namespace. Most methods in the \fBsocketio.Server\fP
class have the optional \fBnamespace\fP argument.
.SS Class\-Based Namespaces
.sp
As an alternative to the decorator\-based namespaces, the event handlers that
belong to a namespace can be created as methods in a subclass of
\fBsocketio.Namespace\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
class MyCustomNamespace(socketio.Namespace):
    def on_connect(self, sid, environ):
        pass

    def on_disconnect(self, sid, reason):
        pass

    def on_my_event(self, sid, data):
        self.emit(\(aqmy_response\(aq, data)

sio.register_namespace(MyCustomNamespace(\(aq/test\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
For asyncio based servers, namespaces must inherit from
\fBsocketio.AsyncNamespace\fP, and can define event handlers as coroutines
if desired:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
class MyCustomNamespace(socketio.AsyncNamespace):
    def on_connect(self, sid, environ):
        pass

    def on_disconnect(self, sid, reason):
        pass

    async def on_my_event(self, sid, data):
        await self.emit(\(aqmy_response\(aq, data)

sio.register_namespace(MyCustomNamespace(\(aq/test\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
When class\-based namespaces are used, any events received by the server are
dispatched to a method named as the event name with the \fBon_\fP prefix. For
example, event \fBmy_event\fP will be handled by a method named \fBon_my_event\fP\&.
If an event is received for which there is no corresponding method defined in
the namespace class, then the event is ignored. All event names used in
class\-based namespaces must use characters that are legal in method names.
.sp
As a convenience to methods defined in a class\-based namespace, the namespace
instance includes versions of several of the methods in the
\fBsocketio.Server\fP and \fBsocketio.AsyncServer\fP classes that default
to the proper namespace when the \fBnamespace\fP argument is not given.
.sp
In the case that an event has a handler in a class\-based namespace, and also a
decorator\-based function handler, only the standalone function handler is
invoked.
.sp
It is important to note that class\-based namespaces are singletons. This means
that a single instance of a namespace class is used for all clients, and
consequently, a namespace instance cannot be used to store client specific
information.
.SS Catch\-All Namespaces
.sp
Similarily to catch\-all event handlers, a \(dqcatch\-all\(dq namespace can be used
when defining event handlers for any connected namespaces that do not have an
explicitly defined event handler. As with catch\-all events, \fB\(aq*\(aq\fP is used in
place of a namespace:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aqmy_event\(aq, namespace=\(aq*\(aq)
def my_event_any_namespace(namespace, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
For these events, the namespace is passed as first argument, followed by the
regular arguments of the event.
.sp
A catch\-all class\-based namespace handler can be defined by passing \fB\(aq*\(aq\fP as
the namespace during registration:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio.register_namespace(MyCustomNamespace(\(aq*\(aq))
.EE
.UNINDENT
.UNINDENT
.sp
A \(dqcatch\-all\(dq handler for all events on all namespaces can be defined as
follows:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.on(\(aq*\(aq, namespace=\(aq*\(aq)
def any_event_any_namespace(event, namespace, sid, data):
    pass
.EE
.UNINDENT
.UNINDENT
.sp
Event handlers with catch\-all events and namespaces receive the event name and
the namespace as first and second arguments.
.SS User Sessions
.sp
The server can maintain application\-specific information in a user session
dedicated to each connected client. Applications can use the user session to
write any details about the user that need to be preserved throughout the life
of the connection, such as usernames or user ids.
.sp
The \fBsave_session()\fP and \fBget_session()\fP methods are used to store and
retrieve information in the user session:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def connect(sid, environ):
    username = authenticate_user(environ)
    sio.save_session(sid, {\(aqusername\(aq: username})

@sio.event
def message(sid, data):
    session = sio.get_session(sid)
    print(\(aqmessage from \(aq, session[\(aqusername\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP server, these methods are coroutines:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
async def connect(sid, environ):
    username = authenticate_user(environ)
    await sio.save_session(sid, {\(aqusername\(aq: username})

@sio.event
async def message(sid, data):
    session = await sio.get_session(sid)
    print(\(aqmessage from \(aq, session[\(aqusername\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
The session can also be manipulated with the \fIsession()\fP context manager:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
def connect(sid, environ):
    username = authenticate_user(environ)
    with sio.session(sid) as session:
        session[\(aqusername\(aq] = username

@sio.event
def message(sid, data):
    with sio.session(sid) as session:
        print(\(aqmessage from \(aq, session[\(aqusername\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP server, an asynchronous context manager is used:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@sio.event
async def connect(sid, environ):
    username = authenticate_user(environ)
    async with sio.session(sid) as session:
        session[\(aqusername\(aq] = username

@sio.event
async def message(sid, data):
    async with sio.session(sid) as session:
        print(\(aqmessage from \(aq, session[\(aqusername\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
The \fBget_session()\fP, \fBsave_session()\fP and \fBsession()\fP methods take an
optional \fBnamespace\fP argument. If this argument isn\(aqt provided, the session
is attached to the default namespace.
.sp
Note: the contents of the user session are destroyed when the client
disconnects. In particular, user session contents are not preserved when a
client reconnects after an unexpected disconnection from the server.
.SS Cross\-Origin Controls
.sp
For security reasons, this server enforces a same\-origin policy by default. In
practical terms, this means the following:
.INDENT 0.0
.IP \(bu 2
If an incoming HTTP or WebSocket request includes the \fBOrigin\fP header,
this header must match the scheme and host of the connection URL. In case
of a mismatch, a 400 status code response is returned and the connection is
rejected.
.IP \(bu 2
No restrictions are imposed on incoming requests that do not include the
\fBOrigin\fP header.
.UNINDENT
.sp
If necessary, the \fBcors_allowed_origins\fP option can be used to allow other
origins. This argument can be set to a string to set a single allowed origin, or
to a list to allow multiple origins. A special value of \fB\(aq*\(aq\fP can be used to
instruct the server to allow all origins, but this should be done with care, as
this could make the server vulnerable to Cross\-Site Request Forgery (CSRF)
attacks.
.SS Monitoring and Administration
.sp
The Socket.IO server can be configured to accept connections from the official
\X'tty: link https://socket.io/docs/v4/admin-ui/'\fI\%Socket.IO Admin UI\fP\X'tty: link'\&. This tool provides
real\-time information about currently connected clients, rooms in use and
events being emitted. It also allows an administrator to manually emit events,
change room assignments and disconnect clients. The hosted version of this tool
is available at \X'tty: link https://admin.socket.io'\fI\%https://admin.socket.io\fP\X'tty: link'\&.
.sp
Given that enabling this feature can affect the performance of the server, it
is disabled by default. To enable it, call the
\fBinstrument()\fP method. For example:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import os
import socketio

sio = socketio.Server(cors_allowed_origins=[
    \(aqhttp://localhost:5000\(aq,
    \(aqhttps://admin.socket.io\(aq,
])
sio.instrument(auth={
    \(aqusername\(aq: \(aqadmin\(aq,
    \(aqpassword\(aq: os.environ[\(aqADMIN_PASSWORD\(aq],
})
.EE
.UNINDENT
.UNINDENT
.sp
This configures the server to accept connections from the hosted Admin UI
client. Administrators can then open \X'tty: link https://admin.socket.io'\fI\%https://admin.socket.io\fP\X'tty: link' in their web
browsers and log in with username \fBadmin\fP and the password given by the
\fBADMIN_PASSWORD\fP environment variable. To ensure the Admin UI front end is
allowed to connect, CORS is also configured.
.sp
Consult the reference documentation to learn about additional configuration
options that are available.
.SS Debugging and Troubleshooting
.sp
To help you debug issues, the server can be configured to output logs to the
terminal:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import socketio

# standard Python
sio = socketio.Server(logger=True, engineio_logger=True)

# asyncio
sio = socketio.AsyncServer(logger=True, engineio_logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument controls logging related to the Socket.IO protocol,
while \fBengineio_logger\fP controls logs that originate in the low\-level
Engine.IO transport. These arguments can be set to \fBTrue\fP to output logs to
\fBstderr\fP, or to an object compatible with Python\(aqs \fBlogging\fP package
where the logs should be emitted to. A value of \fBFalse\fP disables logging.
.sp
Logging can help identify the cause of connection problems, 400 responses,
bad performance and other issues.
.SS Concurrency and Web Server Integration
.sp
The Socket.IO server can be configured with different concurrency models
depending on the needs of the application and the web server that is used. The
concurrency model is given by the \fBasync_mode\fP argument in the server. For
example:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqthreading\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The following sub\-sections describe the available concurrency options for
synchronous and asynchronous servers.
.SS Standard Modes
.INDENT 0.0
.IP \(bu 2
\fBthreading\fP: the server will use Python threads for concurrency and will
run on any multi\-threaded WSGI server. This is the default mode when no other
concurrency libraries are installed.
.IP \(bu 2
\fBgevent\fP: the server will use greenlets through the
\X'tty: link http://www.gevent.org/'\fI\%gevent\fP\X'tty: link' library for concurrency. A web server that
is compatible with \fBgevent\fP is required.
.IP \(bu 2
\fBgevent_uwsgi\fP: a variation of the \fBgevent\fP mode that is designed to work
with the \X'tty: link https://uwsgi-docs.readthedocs.io/en/latest/'\fI\%uWSGI\fP\X'tty: link' web server.
.IP \(bu 2
\fBeventlet\fP: the server will use greenlets through the
\X'tty: link http://eventlet.net/'\fI\%eventlet\fP\X'tty: link' library for concurrency. A web server that
is compatible with \fBeventlet\fP is required. Use of \fBeventlet\fP is not
recommended due to this project being in maintenance mode.
.UNINDENT
.SS Asyncio Modes
.sp
The asynchronous options are all based on the
\X'tty: link https://docs.python.org/3/library/asyncio.html'\fI\%asyncio\fP\X'tty: link' package of the
Python standard library, with minor variations depending on the web server
platform that is used.
.INDENT 0.0
.IP \(bu 2
\fBasgi\fP: use of any
\X'tty: link https://asgi.readthedocs.io/en/latest/'\fI\%ASGI\fP\X'tty: link' web server is required.
.IP \(bu 2
\fBaiohttp\fP: use of the \X'tty: link http://aiohttp.readthedocs.io/'\fI\%aiohttp\fP\X'tty: link' web
framework and server is required.
.IP \(bu 2
\fBtornado\fP: use of the \X'tty: link http://www.tornadoweb.org/'\fI\%Tornado\fP\X'tty: link' web framework
and server is required.
.IP \(bu 2
\fBsanic\fP: use of the \X'tty: link http://sanic.readthedocs.io/'\fI\%Sanic\fP\X'tty: link' web framework
and server is required. When using Sanic, it is recommended to use the
\fBasgi\fP mode instead.
.UNINDENT
.SS Deployment Strategies
.sp
The following sections describe a variety of deployment strategies for
Socket.IO servers.
.SS Gunicorn
.sp
The simplest deployment strategy for the Socket.IO server is to use the popular
\X'tty: link http://gunicorn.org'\fI\%Gunicorn\fP\X'tty: link' web server in multi\-threaded mode. The
Socket.IO server must be wrapped by the \fBsocketio.WSGIApp\fP class, so
that it is compatible with the WSGI protocol:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqthreading\(aq)
app = socketio.WSGIApp(sio)
.EE
.UNINDENT
.UNINDENT
.sp
If desired, the \fBsocketio.WSGIApp\fP class can forward any traffic that is not
Socket.IO to another WSGI application, making it possible to deploy a standard
WSGI web application built with frameworks such as Flask or Django and the
Socket.IO server as a bundle:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqthreading\(aq)
app = socketio.WSGIApp(sio, other_wsgi_app)
.EE
.UNINDENT
.UNINDENT
.sp
The example that follows shows how to start a Socket.IO application using
Gunicorn\(aqs threaded worker class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ gunicorn \-\-workers 1 \-\-threads 100 \-\-bind 127.0.0.1:5000 module:app
.EE
.UNINDENT
.UNINDENT
.sp
With the above configuration the server will be able to handle close to 100
concurrent clients.
.sp
It is also possible to use more than one worker process, but this has two
additional requirements:
.INDENT 0.0
.IP \(bu 2
The clients must connect directly over WebSocket. The long\-polling transport
is incompatible with the way Gunicorn load balances requests among workers.
To disable long\-polling in the server, add \fBtransports=[\(aqwebsocket\(aq]\fP in
the server constructor. Clients will have a similar option to initiate the
connection with WebSocket.
.IP \(bu 2
The \fBsocketio.Server()\fP instances in each worker must be configured with
a message queue to allow the workers to communicate with each other. See the
\fI\%Using a Message Queue\fP section for more information.
.UNINDENT
.sp
When using multiple workers, the approximate number of connections the server
will be able to accept can be calculated as the number of workers multiplied by
the number of threads per worker.
.sp
Note that Gunicorn can also be used alongside \fBuvicorn\fP, \fBgevent\fP and
\fBeventlet\fP\&. These options are discussed under the appropriate sections below.
.SS Uvicorn (and other ASGI web servers)
.sp
When working with an asynchronous Socket.IO server, the easiest deployment
strategy is to use an ASGI web server such as
\X'tty: link https://www.uvicorn.org/'\fI\%Uvicorn\fP\X'tty: link'\&.
.sp
The \fBsocketio.ASGIApp\fP class is an ASGI compatible application that can
forward Socket.IO traffic to a \fBsocketio.AsyncServer\fP instance:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.AsyncServer(async_mode=\(aqasgi\(aq)
app = socketio.ASGIApp(sio)
.EE
.UNINDENT
.UNINDENT
.sp
If desired, the \fBsocketio.ASGIApp\fP class can forward any traffic that is not
Socket.IO to another ASGI application, making it possible to deploy a standard
ASGI web application built with a framework such as FastAPI and the Socket.IO
server as a bundle:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.AsyncServer(async_mode=\(aqasgi\(aq)
app = socketio.ASGIApp(sio, other_asgi_app)
.EE
.UNINDENT
.UNINDENT
.sp
The following example starts the application with Uvicorn:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
uvicorn \-\-port 5000 module:app
.EE
.UNINDENT
.UNINDENT
.sp
Uvicorn can also be used through its Gunicorn worker:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
gunicorn \-\-workers 1 \-\-worker\-class uvicorn.workers.UvicornWorker \-\-bind 127.0.0.1:5000
.EE
.UNINDENT
.UNINDENT
.sp
See the Gunicorn section above for information on how to use Gunicorn with
multiple workers.
.SS Hypercorn, Daphne, and other ASGI servers
.sp
To use an ASGI web server other than Uvicorn, configure the application for
ASGI as shown above for Uvicorn, then follow the documentation of your chosen
web server to start the application.
.SS Aiohttp
.sp
Another option for deploying an asynchronous Socket.IO server is to use the
\X'tty: link http://aiohttp.readthedocs.io/'\fI\%Aiohttp\fP\X'tty: link' web framework and server. Instances
of class \fBsocketio.AsyncServer\fP will automatically use Aiohttp
if the library is installed. To request its use explicitly, the \fBasync_mode\fP
option can be given in the constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.AsyncServer(async_mode=\(aqaiohttp\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for Aiohttp must be attached to an existing application:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = web.Application()
sio.attach(app)
.EE
.UNINDENT
.UNINDENT
.sp
The Aiohttp application can define regular routes that will coexist with the
Socket.IO server. A typical pattern is to add routes that serve a client
application and any associated static files.
.sp
The Aiohttp application is then executed in the usual manner:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
if __name__ == \(aq__main__\(aq:
    web.run_app(app)
.EE
.UNINDENT
.UNINDENT
.SS Gevent
.sp
When a multi\-threaded web server is unable to satisfy the concurrency and
scalability requirements of the application, an option to try is
\X'tty: link http://www.gevent.org'\fI\%Gevent\fP\X'tty: link'\&. Gevent is a coroutine\-based concurrency library
based on greenlets, which are significantly lighter than threads.
.sp
Instances of class \fBsocketio.Server\fP will automatically use Gevent if the
library is installed. To request gevent to be selected explicitly, the
\fBasync_mode\fP option can be given in the constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqgevent\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The Socket.IO server must be wrapped by the \fBsocketio.WSGIApp\fP class, so
that it is compatible with the WSGI protocol:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = socketio.WSGIApp(sio)
.EE
.UNINDENT
.UNINDENT
.sp
If desired, the \fBsocketio.WSGIApp\fP class can forward any traffic that is not
Socket.IO to another WSGI application, making it possible to deploy a standard
WSGI web application built with frameworks such as Flask or Django and the
Socket.IO server as a bundle:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqgevent\(aq)
app = socketio.WSGIApp(sio, other_wsgi_app)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for Gevent is deployed as a regular WSGI application
using the provided \fBsocketio.WSGIApp\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from gevent import pywsgi

pywsgi.WSGIServer((\(aq\(aq, 8000), app).serve_forever()
.EE
.UNINDENT
.UNINDENT
.SS Gevent with Gunicorn
.sp
An alternative to running the gevent WSGI server as above is to use
\fI\%Gunicorn\fP with its Gevent worker. The command to launch the
application under Gunicorn and Gevent is shown below:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ gunicorn \-k gevent \-w 1 \-b 127.0.0.1:5000 module:app
.EE
.UNINDENT
.UNINDENT
.sp
See the Gunicorn section above for information on how to use Gunicorn with
multiple workers.
.sp
Gevent provides a \fBmonkey_patch()\fP function that replaces all the blocking
functions in the standard library with equivalent asynchronous versions. While
the Socket.IO server does not require monkey patching, other libraries such as
database or message queue drivers are likely to require it.
.SS Gevent with uWSGI
.sp
When using the uWSGI server in combination with gevent, the Socket.IO server
can take advantage of uWSGI\(aqs native WebSocket support.
.sp
Instances of class \fBsocketio.Server\fP will automatically use this option for
asynchronous operations if both gevent and uWSGI are installed and eventlet is
not installed. To request this asynchronous mode explicitly, the
\fBasync_mode\fP option can be given in the constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# gevent with uWSGI
sio = socketio.Server(async_mode=\(aqgevent_uwsgi\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A complete explanation of the configuration and usage of the uWSGI server is
beyond the scope of this documentation. The uWSGI server is a fairly complex
package that provides a large and comprehensive set of options. It must be
compiled with WebSocket and SSL support for the WebSocket transport to be
available. As way of an introduction, the following command starts a uWSGI
server for the \fBlatency.py\fP example on port 5000:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ uwsgi \-\-http :5000 \-\-gevent 1000 \-\-http\-websockets \-\-master \-\-wsgi\-file latency.py \-\-callable app
.EE
.UNINDENT
.UNINDENT
.SS Tornado
.sp
Instances of class \fBsocketio.AsyncServer\fP will automatically use
\X'tty: link http://www.tornadoweb.org//'\fI\%Tornado\fP\X'tty: link' if the library is installed. To
request its use explicitly, the \fBasync_mode\fP option can be given in the
constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.AsyncServer(async_mode=\(aqtornado\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for Tornado must include a request handler for
Socket.IO:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = tornado.web.Application(
    [
        (r\(dq/socket.io/\(dq, socketio.get_tornado_handler(sio)),
    ],
    # ... other application options
)
.EE
.UNINDENT
.UNINDENT
.sp
The Tornado application can define other routes that will coexist with the
Socket.IO server. A typical pattern is to add routes that serve a client
application and any associated static files.
.sp
The Tornado application is then executed in the usual manner:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app.listen(port)
tornado.ioloop.IOLoop.current().start()
.EE
.UNINDENT
.UNINDENT
.SS Eventlet
.sp
\fBNOTE:\fP
.INDENT 0.0
.INDENT 3.5
Eventlet is not in active development anymore, and for that reason the
current recommendation is to not use it for new projects.
.UNINDENT
.UNINDENT
.sp
\X'tty: link http://eventlet.net/'\fI\%Eventlet\fP\X'tty: link' is a high performance concurrent networking
library for Python that uses coroutines, enabling code to be written in the
same style used with the blocking standard library functions. An Socket.IO
server deployed with eventlet has access to the long\-polling and WebSocket
transports.
.sp
Instances of class \fBsocketio.Server\fP will automatically use eventlet for
asynchronous operations if the library is installed. To request its use
explicitly, the \fBasync_mode\fP option can be given in the constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
sio = socketio.Server(async_mode=\(aqeventlet\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for eventlet is deployed as a regular WSGI application
using the provided \fBsocketio.WSGIApp\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import eventlet

app = socketio.WSGIApp(sio)
eventlet.wsgi.server(eventlet.listen((\(aq\(aq, 8000)), app)
.EE
.UNINDENT
.UNINDENT
.SS Eventlet with Gunicorn
.sp
An alternative to running the eventlet WSGI server as above is to use
\fI\%gunicorn\fP, a fully featured pure Python web server. The
command to launch the application under gunicorn is shown below:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ gunicorn \-k eventlet \-w 1 module:app
.EE
.UNINDENT
.UNINDENT
.sp
See the Gunicorn section above for information on how to use Gunicorn with
multiple workers.
.sp
Eventlet provides a \fBmonkey_patch()\fP function that replaces all the blocking
functions in the standard library with equivalent asynchronous versions. While
python\-socketio does not require monkey patching, other libraries such as
database drivers are likely to require it.
.SS Sanic
.sp
\fBNOTE:\fP
.INDENT 0.0
.INDENT 3.5
The Sanic integration has not been updated in a long time. It is currently
recommended that a Sanic application is deployed with the ASGI integration.
.UNINDENT
.UNINDENT
.SS Using a Message Queue
.sp
When working with distributed applications, it is often necessary to access
the functionality of the Socket.IO from multiple processes. There are two
specific use cases:
.INDENT 0.0
.IP \(bu 2
Highly available applications may want to use horizontal scaling of the
Socket.IO server to be able to handle very large number of concurrent
clients.
.IP \(bu 2
Applications that use work queues such as
\X'tty: link http://www.celeryproject.org/'\fI\%Celery\fP\X'tty: link' may need to emit an event to a
client once a background job completes. The most convenient place to carry
out this task is the worker process that handled this job.
.UNINDENT
.sp
As a solution to the above problems, the Socket.IO server can be configured
to connect to a message queue such as \X'tty: link http://redis.io/'\fI\%Redis\fP\X'tty: link' or
\X'tty: link https://www.rabbitmq.com/'\fI\%RabbitMQ\fP\X'tty: link', to communicate with other related
Socket.IO servers or auxiliary workers.
.SS Redis
.sp
To use a Redis message queue, a Python Redis client must be installed:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# socketio.Server class
pip install redis
.EE
.UNINDENT
.UNINDENT
.sp
The Redis queue is configured through the \fBsocketio.RedisManager\fP and
\fBsocketio.AsyncRedisManager\fP classes. These classes connect directly to
the Redis store and use the queue\(aqs pub/sub functionality:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# socketio.Server class
mgr = socketio.RedisManager(\(aqredis://\(aq)
sio = socketio.Server(client_manager=mgr)

# socketio.AsyncServer class
mgr = socketio.AsyncRedisManager(\(aqredis://\(aq)
sio = socketio.AsyncServer(client_manager=mgr)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBclient_manager\fP argument instructs the server to connect to the given
message queue, and to coordinate with other processes connected to the queue.
.SS Kombu
.sp
\X'tty: link http://kombu.readthedocs.org/en/latest/'\fI\%Kombu\fP\X'tty: link' is a Python package that
provides access to RabbitMQ and many other message queues. It can be installed
with pip:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install kombu
.EE
.UNINDENT
.UNINDENT
.sp
To use RabbitMQ or other AMQP protocol compatible queues, that is the only
required dependency. But for other message queues, Kombu may require
additional packages. For example, to use a Redis queue via Kombu, the Python
package for Redis needs to be installed as well:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install redis
.EE
.UNINDENT
.UNINDENT
.sp
The queue is configured through the \fBsocketio.KombuManager\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
mgr = socketio.KombuManager(\(aqamqp://\(aq)
sio = socketio.Server(client_manager=mgr)
.EE
.UNINDENT
.UNINDENT
.sp
The connection URL passed to the \fBKombuManager\fP constructor is passed
directly to Kombu\(aqs \X'tty: link http://kombu.readthedocs.org/en/latest/userguide/connections.html'\fI\%Connection object\fP\X'tty: link', so
the Kombu documentation should be consulted for information on how to build
the correct URL for a given message queue.
.sp
Note that Kombu currently does not support asyncio, so it cannot be used with
the \fBsocketio.AsyncServer\fP class.
.SS Kafka
.sp
\X'tty: link https://kafka.apache.org/'\fI\%Apache Kafka\fP\X'tty: link' is supported through the
\X'tty: link https://kafka-python.readthedocs.io/en/master/index.html'\fI\%kafka\-python\fP\X'tty: link'
package:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install kafka\-python
.EE
.UNINDENT
.UNINDENT
.sp
Access to Kafka is configured through the \fBsocketio.KafkaManager\fP
class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
mgr = socketio.KafkaManager(\(aqkafka://\(aq)
sio = socketio.Server(client_manager=mgr)
.EE
.UNINDENT
.UNINDENT
.sp
Note that Kafka currently does not support asyncio, so it cannot be used with
the \fBsocketio.AsyncServer\fP class.
.SS AioPika
.sp
A RabbitMQ message queue is supported in asyncio applications through the
\X'tty: link https://aio-pika.readthedocs.io/en/latest/'\fI\%AioPika\fP\X'tty: link' package::
You need to install aio_pika with pip:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install aio_pika
.EE
.UNINDENT
.UNINDENT
.sp
The RabbitMQ queue is configured through the
\fBsocketio.AsyncAioPikaManager\fP class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
mgr = socketio.AsyncAioPikaManager(\(aqamqp://\(aq)
sio = socketio.AsyncServer(client_manager=mgr)
.EE
.UNINDENT
.UNINDENT
.SS Horizontal Scaling
.sp
Socket.IO is a stateful protocol, which makes horizontal scaling more
difficult. When deploying a cluster of Socket.IO processes, all processes must
connect to the message queue by passing the \fBclient_manager\fP argument to the
server instance. This enables the workers to communicate and coordinate complex
operations such as broadcasts.
.sp
If the long\-polling transport is used, then there are two additional
requirements that must be met:
.INDENT 0.0
.IP \(bu 2
Each Socket.IO process must be able to handle multiple requests
concurrently. This is needed because long\-polling clients send two
requests in parallel. Worker processes that can only handle one request at a
time are not supported.
.IP \(bu 2
The load balancer must be configured to always forward requests from a
client to the same worker process, so that all requests coming from a client
are handled by the same node. Load balancers call this \fIsticky sessions\fP, or
\fIsession affinity\fP\&.
.UNINDENT
.SS Emitting from external processes
.sp
To have a process other than a server connect to the queue to emit a message,
the same client manager classes can be used as standalone objects. In this
case, the \fBwrite_only\fP argument should be set to \fBTrue\fP to disable the
creation of a listening thread, which only makes sense in a server. For
example:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# connect to the redis queue as an external process
external_sio = socketio.RedisManager(\(aqredis://\(aq, write_only=True)

# emit an event
external_sio.emit(\(aqmy event\(aq, data={\(aqfoo\(aq: \(aqbar\(aq}, room=\(aqmy room\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A limitation of the write\-only client manager object is that it cannot receive
callbacks when emitting. When the external process needs to receive callbacks,
using a client to connect to the server with read and write support is a better
option than a write\-only client manager.
.SH API REFERENCE
.INDENT 0.0
.IP \(bu 2
\fI\%Index\fP
.IP \(bu 2
\fI\%Module Index\fP
.IP \(bu 2
\fI\%Search Page\fP
.UNINDENT
.SH AUTHOR
Miguel Grinberg
.SH COPYRIGHT
2018, Miguel Grinberg
.\" Generated by docutils manpage writer.
.