File: python-engineio.1

package info (click to toggle)
python-engineio 4.12.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 944 kB
  • sloc: python: 10,594; makefile: 15; sh: 6
file content (1480 lines) | stat: -rw-r--r-- 41,565 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
.\" 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-ENGINEIO" "1" "May 19, 2025" "" "python-engineio"
.SH NAME
python-engineio \- python-engineio Documentation
.sp
This project implements Python based Engine.IO client and server that can run
standalone or integrated with a variety of Python web frameworks and
applications.
.SH GETTING STARTED
.SS What is Engine.IO?
.sp
Engine.IO is a lightweight 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 \fBasyncio\fP variants.
.sp
The Engine.IO protocol is extremely simple. Once a connection between a client
and a server is established, either side can send \(dqmessages\(dq to the other
side. Event handlers provided by the applications on both ends are invoked
when a message is received, or when a connection is established or dropped.
.SS Client Examples
.sp
The example that follows shows a simple Python client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio

eio = engineio.Client()

@eio.on(\(aqconnect\(aq)
def on_connect():
    print(\(aqconnection established\(aq)

@eio.on(\(aqmessage\(aq)
def on_message(data):
    print(\(aqmessage received with \(aq, data)
    eio.send({\(aqresponse\(aq: \(aqmy response\(aq})

@eio.on(\(aqdisconnect\(aq)
def on_disconnect():
    print(\(aqdisconnected from server\(aq)

eio.connect(\(aqhttp://localhost:5000\(aq)
eio.wait()
.EE
.UNINDENT
.UNINDENT
.sp
And here is a similar client written using the official Engine.IO Javascript
client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
<script src=\(dq/path/to/engine.io.js\(dq></script>
<script>
    var socket = eio(\(aqhttp://localhost:5000\(aq);
    socket.on(\(aqopen\(aq, function() { console.log(\(aqconnection established\(aq); });
    socket.on(\(aqmessage\(aq, function(data) {
        console.log(\(aqmessage received with \(aq + data);
        socket.send({response: \(aqmy response\(aq});
    });
    socket.on(\(aqclose\(aq, function() { console.log(\(aqdisconnected from server\(aq); });
</script>
.EE
.UNINDENT
.UNINDENT
.SS Client Features
.INDENT 0.0
.IP \(bu 2
Can connect to other Engine.IO complaint servers besides the one in this package.
.IP \(bu 2
Compatible with Python 3.6+.
.IP \(bu 2
Two versions of the client, one for standard Python and another for \fBasyncio\fP\&.
.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.
.UNINDENT
.SS Server Examples
.sp
The following application is a basic example that uses the Eventlet
asynchronous server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio
import eventlet

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

@eio.on(\(aqconnect\(aq)
def connect(sid, environ):
    print(\(dqconnect \(dq, sid)

@eio.on(\(aqmessage\(aq)
def message(sid, data):
    print(\(dqmessage \(dq, data)
    eio.send(sid, \(aqreply\(aq)

@eio.on(\(aqdisconnect\(aq)
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 asyncio and the Uvicorn web server:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio
import uvicorn

eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files={
    \(aq/\(aq: {\(aqcontent_type\(aq: \(aqtext/html\(aq, \(aqfilename\(aq: \(aqindex.html\(aq}
})

@eio.on(\(aqconnect\(aq)
def connect(sid, environ):
    print(\(dqconnect \(dq, sid)

@eio.on(\(aqmessage\(aq)
async def message(sid, data):
    print(\(dqmessage \(dq, data)
    await eio.send(sid, \(aqreply\(aq)

@eio.on(\(aqdisconnect\(aq)
def disconnect(sid):
    print(\(aqdisconnect \(aq, sid)

if __name__ == \(aq__main__\(aq:
    uvicorn.run(\(aq127.0.0.1\(aq, 5000)
.EE
.UNINDENT
.UNINDENT
.SS Server Features
.INDENT 0.0
.IP \(bu 2
Can accept clients running other complaint Engine.IO clients besides the one in this
package.
.IP \(bu 2
Compatible with Python 3.6+.
.IP \(bu 2
Two versions of the server, one for standard Python and another for \fBasyncio\fP\&.
.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' and
\X'tty: link https://asgi.readthedocs.io/en/latest/'\fI\%ASGI\fP\X'tty: link' web servers includind
\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://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 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
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
Supports XHR2 and XHR browsers as clients.
.IP \(bu 2
Supports text and binary messages.
.IP \(bu 2
Supports gzip and deflate HTTP compression.
.IP \(bu 2
Configurable CORS responses to avoid cross\-origin problems with browsers.
.UNINDENT
.SH THE ENGINE.IO CLIENT
.sp
This package contains two Engine.IO clients:
.INDENT 0.0
.IP \(bu 2
The \fBengineio.Client()\fP class creates a client compatible with the
standard Python library.
.IP \(bu 2
The \fBengineio.AsyncClient()\fP class creates a client compatible with
the \fBasyncio\fP package.
.UNINDENT
.sp
The methods in the two clients are the same, with the only difference that in
the \fBasyncio\fP client most methods are implemented as coroutines.
.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\-engineio[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\-engineio[asyncio_client]\(dq
.EE
.UNINDENT
.UNINDENT
.SS Creating a Client Instance
.sp
To instantiate an Engine.IO client, simply create an instance of the
appropriate client class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio

# standard Python
eio = engineio.Client()

# asyncio
eio = engineio.AsyncClient()
.EE
.UNINDENT
.UNINDENT
.SS Defining Event Handlers
.sp
To responds to events triggered by the connection or the server, event Handler
functions must be defined using the \fBon\fP decorator:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqconnect\(aq)
def on_connect():
    print(\(aqI\(aqm connected!\(aq)

@eio.on(\(aqmessage\(aq)
def on_message(data):
    print(\(aqI received a message!\(aq)

@eio.on(\(aqdisconnect\(aq)
def on_disconnect(reason):
    print(\(aqI\(aqm disconnected! reason:\(aq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP server, event handlers can be regular functions as above,
or can also be coroutines:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqmessage\(aq)
async def on_message(data):
    print(\(aqI received a message!\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The argument given to the \fBon\fP decorator is the event name. The events that
are supported are \fBconnect\fP, \fBmessage\fP and \fBdisconnect\fP\&.
.sp
The \fBdata\fP argument passed to the \fB\(aqmessage\(aq\fP event handler contains
application\-specific data provided by the server with the event.
.sp
The \fBdisconnect\fP handler is invoked for client initiated disconnects, server
initiated disconnects, or accidental disconnects, for example due to
networking failures. The argument passed to this handler provides the
disconnect reason. Example:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqdisconnect\(aq)
def on_disconnect(reason):
    if reason == eio.reason.CLIENT_DISCONNECT:
        print(\(aqclient disconnection\(aq)
    elif reason == eio.reason.SERVER_DISCONNECT:
        print(\(aqthe server kicked me out\(aq)
    else:
        print(f\(aqdisconnect reason: {reason}\(aq)
.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
eio.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 eio.connect(\(aqhttp://localhost:5000\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
Upon connection, the server assigns the client a unique session identifier.
The applicaction can find this identifier in the \fBsid\fP attribute:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
print(\(aqmy sid is\(aq, eio.sid)
.EE
.UNINDENT
.UNINDENT
.SS Sending Messages
.sp
The client can send a message to the server using the \fBsend()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio.send({\(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 eio.send({\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
The single argument provided to the method is the data that is passed on
to the server. The data can be of type \fBstr\fP, \fBbytes\fP, \fBdict\fP or
\fBlist\fP\&. The data included inside dictionaries and lists is also
constrained to these types.
.sp
The \fBsend()\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 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
eio.disconnect()
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP client this is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await eio.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 Engine.IO
client.
.sp
If the application does not have anything to do in the main thread and
just wants to wait until the connection ends, it can call the \fBwait()\fP
method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio.wait()
.EE
.UNINDENT
.UNINDENT
.sp
Or in the \fBasyncio\fP version:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await eio.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

eio.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

eio.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, but the background function is.
.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
eio.sleep(2)
.EE
.UNINDENT
.UNINDENT
.sp
Or for \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await eio.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 engineio

# standard Python
eio = engineio.Client(logger=True)

# asyncio
eio = engineio.AsyncClient(logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument 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 ENGINE.IO SERVER
.sp
This package contains two Engine.IO servers:
.INDENT 0.0
.IP \(bu 2
The \fBengineio.Server()\fP class creates a server compatible with the
standard Python library.
.IP \(bu 2
The \fBengineio.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 Python Engine.IO server use the following command:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
pip install \(dqpython\-engineio\(dq
.EE
.UNINDENT
.UNINDENT
.sp
In addition to the server, you will need to select an asynchronous framework
or server to use along with it. The list of supported packages is covered
in the \fI\%Deployment Strategies\fP section.
.SS Creating a Server Instance
.sp
An Engine.IO server is an instance of class \fBengineio.Server\fP\&. This
instance can be transformed into a standard WSGI application by wrapping it
with the \fBengineio.WSGIApp\fP class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio

# create a Engine.IO server
eio = engineio.Server()

# wrap with a WSGI application
app = engineio.WSGIApp(eio)
.EE
.UNINDENT
.UNINDENT
.sp
For asyncio based servers, the \fBengineio.AsyncServer\fP class provides
the same functionality, but in a coroutine friendly format. If desired, The
\fBengineio.ASGIApp\fP class can transform the server into a standard
ASGI application:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# create a Engine.IO server
eio = engineio.AsyncServer()

# wrap with ASGI application
app = engineio.ASGIApp(eio)
.EE
.UNINDENT
.UNINDENT
.sp
These two wrappers can also act as middlewares, forwarding any traffic that is
not intended to the Engine.IO server to another application. This allows
Engine.IO servers to integrate easily into existing WSGI or ASGI applications:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from wsgi import app  # a Flask, Django, etc. application
app = engineio.WSGIApp(eio, app)
.EE
.UNINDENT
.UNINDENT
.SS Serving Static Files
.sp
The Engine.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/engine.io.js\(aq: \(aqstatic/engine.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 \fBengineio.WSGIApp\fP or \fBengineio.ASGIApp\fP classes:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# for standard WSGI applications
eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files=static_files)

# for asyncio\-based ASGI applications
eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, 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 Engine.IO path.
.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 Engine.IO path 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 Defining Event Handlers
.sp
To responds to events triggered by the connection or the client, event Handler
functions must be defined using the \fBon\fP decorator:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqconnect\(aq)
def on_connect(sid):
    print(\(aqA client connected!\(aq)

@eio.on(\(aqmessage\(aq)
def on_message(sid, data):
    print(\(aqI received a message!\(aq)

@eio.on(\(aqdisconnect\(aq)
def on_disconnect(sid, reason):
    print(\(aqClient disconnected! reason:\(aq, reason)
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP server, event handlers can be regular functions as above,
or can also be coroutines:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqmessage\(aq)
async def on_message(sid, data):
    print(\(aqI received a message!\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
The argument given to the \fBon\fP decorator is the event name. The events that
are supported are \fBconnect\fP, \fBmessage\fP and \fBdisconnect\fP\&.
.sp
The \fBsid\fP argument passed into all the event handlers is a connection
identifier for the client. All the events from a client will use the same
\fBsid\fP value.
.sp
The \fBconnect\fP handler is the place where the server can perform
authentication. The value returned by this handler is used to determine if the
connection is accepted or rejected. When the handler does not return any value
(which is the same as returning \fBNone\fP) or when it returns \fBTrue\fP the
connection is accepted. If the handler returns \fBFalse\fP or any JSON
compatible data type (string, integer, list or dictionary) the connection is
rejected. A rejected connection triggers a response with a 401 status code.
.sp
The \fBdata\fP argument passed to the \fB\(aqmessage\(aq\fP event handler contains
application\-specific data provided by the client with the event.
.sp
The \fBdisconnect\fP handler is invoked for client initiated disconnects,
server initiated disconnects, or accidental disconnects, for example due to
networking failures. The second argument passed to this handler provides the
disconnect reason. Example:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
@eio.on(\(aqdisconnect\(aq)
def on_disconnect(sid, reason):
    if reason == eio.reason.CLIENT_DISCONNECT:
        print(\(aqthe client went away\(aq)
    elif reason == eio.reason.SERVER_DISCONNECT:
        print(\(aqthe client was kicked out\(aq)
    else:
        print(f\(aqdisconnect reason: {reason}\(aq)
.EE
.UNINDENT
.UNINDENT
.SS Sending Messages
.sp
The server can send a message to any client using the \fBsend()\fP method:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio.send(sid, {\(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 eio.send(sid, {\(aqfoo\(aq: \(aqbar\(aq})
.EE
.UNINDENT
.UNINDENT
.sp
The first argument provided to the method is the connection identifier for
the recipient client. The second argument is the data that is passed on
to the server. The data can be of type \fBstr\fP, \fBbytes\fP, \fBdict\fP or
\fBlist\fP\&. The data included inside dictionaries and lists is also
constrained to these types.
.sp
The \fBsend()\fP method can be invoked inside an event handler as a response
to a client event, or in any other part of the application, including in
background tasks.
.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
@eio.on(\(aqconnect\(aq)
def on_connect(sid, environ):
    username = authenticate_user(environ)
    eio.save_session(sid, {\(aqusername\(aq: username})

@eio.on(\(aqmessage\(aq)
def on_message(sid, data):
    session = eio.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
@eio.on(\(aqconnect\(aq)
async def on_connect(sid, environ):
    username = authenticate_user(environ)
    await eio.save_session(sid, {\(aqusername\(aq: username})

@eio.on(\(aqmessage\(aq)
async def on_message(sid, data):
    session = await eio.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
@eio.on(\(aqconnect\(aq)
def on_connect(sid, environ):
    username = authenticate_user(environ)
    with eio.session(sid) as session:
        session[\(aqusername\(aq] = username

@eio.on(\(aqmessage\(aq)
def on_message(sid, data):
    with eio.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
@eio.on(\(aqconnect\(aq)
def on_connect(sid, environ):
    username = authenticate_user(environ)
    async with eio.session(sid) as session:
        session[\(aqusername\(aq] = username

@eio.on(\(aqmessage\(aq)
def on_message(sid, data):
    async with eio.session(sid) as session:
        print(\(aqmessage from \(aq, session[\(aqusername\(aq])
.EE
.UNINDENT
.UNINDENT
.sp
Note: the contents of the user session are destroyed when the client
disconnects.
.SS Disconnecting a Client
.sp
At any time the server can disconnect a client from the server by invoking the
\fBdisconnect()\fP method and passing the \fBsid\fP value assigned to the client:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio.disconnect(sid)
.EE
.UNINDENT
.UNINDENT
.sp
For the \fBasyncio\fP client this is a coroutine:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await eio.disconnect(sid)
.EE
.UNINDENT
.UNINDENT
.SS Managing Background Tasks
.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

eio.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

eio.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, but the background function is.
.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
eio.sleep(2)
.EE
.UNINDENT
.UNINDENT
.sp
Or for \fBasyncio\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
await eio.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 server can be configured to output logs to the
terminal:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
import engineio

# standard Python
eio = engineio.Server(logger=True)

# asyncio
eio = engineio.AsyncServer(logger=True)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBlogger\fP argument 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 Deployment Strategies
.sp
The following sections describe a variety of deployment strategies for
Engine.IO servers.
.SS Uvicorn, Daphne, and other ASGI servers
.sp
The \fBengineio.ASGIApp\fP class is an ASGI compatible application that can
forward Engine.IO traffic to an \fBengineio.AsyncServer\fP instance:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio = engineio.AsyncServer(async_mode=\(aqasgi\(aq)
app = engineio.ASGIApp(eio)
.EE
.UNINDENT
.UNINDENT
.sp
If desired, the \fBengineio.ASGIApp\fP class can forward any traffic that is not
Engine.IO to another ASGI application, making it possible to deploy a standard
ASGI web application and the Engine.IO server as a bundle:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio = engineio.AsyncServer(async_mode=\(aqasgi\(aq)
app = engineio.ASGIApp(eio, other_app)
.EE
.UNINDENT
.UNINDENT
.sp
The \fBASGIApp\fP instance is a fully complaint ASGI instance that can be
deployed with an ASGI compatible web server.
.SS Aiohttp
.sp
\X'tty: link http://aiohttp.readthedocs.io/'\fI\%aiohttp\fP\X'tty: link' provides a framework with support
for HTTP and WebSocket, based on asyncio.
.sp
Instances of class \fBengineio.AsyncServer\fP will automatically use aiohttp
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
eio = engineio.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()
eio.attach(app)
.EE
.UNINDENT
.UNINDENT
.sp
The aiohttp application can define regular routes that will coexist with the
Engine.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 Tornado
.sp
\X'tty: link http://www.tornadoweb.org//'\fI\%Tornado\fP\X'tty: link' is a web framework with support
for HTTP and WebSocket. Only Tornado version 5 and newer are supported, thanks
to its tight integration with asyncio.
.sp
Instances of class \fBengineio.AsyncServer\fP will automatically use tornado
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
eio = engineio.AsyncServer(async_mode=\(aqtornado\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for tornado must include a request handler for
Engine.IO:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = tornado.web.Application(
    [
        (r\(dq/engine.io/\(dq, engineio.get_tornado_handler(eio)),
    ],
    # ... other application options
)
.EE
.UNINDENT
.UNINDENT
.sp
The tornado application can define other routes that will coexist with the
Engine.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 Sanic
.sp
Note: Due to some backward incompatible changes introduced in recent versions
of Sanic, it is currently recommended that a Sanic application is deployed with
the ASGI integration instead.
.sp
\X'tty: link http://sanic.readthedocs.io/'\fI\%Sanic\fP\X'tty: link' is a very efficient asynchronous web
server for Python.
.sp
Instances of class \fBengineio.AsyncServer\fP will automatically use Sanic for
asynchronous operations if the framework 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
eio = engineio.AsyncServer(async_mode=\(aqsanic\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for Sanic must be attached to an existing application:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = Sanic()
eio.attach(app)
.EE
.UNINDENT
.UNINDENT
.sp
The Sanic application can define regular routes that will coexist with the
Engine.IO server. A typical pattern is to add routes that serve a client
application and any associated static files to this application.
.sp
The Sanic application is then executed in the usual manner:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
if __name__ == \(aq__main__\(aq:
    app.run()
.EE
.UNINDENT
.UNINDENT
.sp
It has been reported that the CORS support provided by the Sanic extension
\X'tty: link https://github.com/ashleysommer/sanic-cors'\fI\%sanic\-cors\fP\X'tty: link' is incompatible with
this package\(aqs own support for this protocol. To disable CORS support in this
package and let Sanic take full control, initialize the server as follows:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio = engineio.AsyncServer(async_mode=\(aqsanic\(aq, cors_allowed_origins=[])
.EE
.UNINDENT
.UNINDENT
.sp
On the Sanic side you will need to enable the \fICORS_SUPPORTS_CREDENTIALS\fP
setting in addition to any other configuration that you use:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app.config[\(aqCORS_SUPPORTS_CREDENTIALS\(aq] = True
.EE
.UNINDENT
.UNINDENT
.SS Eventlet
.sp
\X'tty: link http://eventlet.net/'\fI\%Eventlet\fP\X'tty: link' is a high performance concurrent networking
library for Python 2 and 3 that uses coroutines, enabling code to be written in
the same style used with the blocking standard library functions. An Engine.IO
server deployed with eventlet has access to the long\-polling and WebSocket
transports.
.sp
Instances of class \fBengineio.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
eio = engineio.Server(async_mode=\(aqeventlet\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for eventlet is deployed as a regular WSGI application
using the provided \fBengineio.WSGIApp\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
app = engineio.WSGIApp(eio)
import eventlet
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
Due to limitations in its load balancing algorithm, gunicorn can only be used
with one worker process, so the \fB\-w 1\fP option is required. Note that a
single eventlet worker can handle a large number of concurrent clients.
.sp
Another limitation when using gunicorn is that the WebSocket transport is not
available, because this transport it requires extensions to the WSGI standard.
.sp
Note: Eventlet provides a \fBmonkey_patch()\fP function that replaces all the
blocking functions in the standard library with equivalent asynchronous
versions. While python\-engineio does not require monkey patching, other
libraries such as database drivers are likely to require it.
.SS Gevent
.sp
\X'tty: link http://gevent.org'\fI\%Gevent\fP\X'tty: link' is another asynchronous framework based on
coroutines, very similar to eventlet. An Engine.IO server deployed with
gevent has access to the long\-polling and websocket transports.
.sp
Instances of class \fBengineio.Server\fP will automatically use gevent for
asynchronous operations if the library is installed and eventlet is not
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
eio = engineio.Server(async_mode=\(aqgevent\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for gevent is deployed as a regular WSGI application
using the provided \fBengineio.WSGIApp\fP:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
from gevent import pywsgi
app = engineio.WSGIApp(eio)
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, 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 gevent \-w 1 module:app
.EE
.UNINDENT
.UNINDENT
.sp
Same as with eventlet, due to limitations in its load balancing algorithm,
gunicorn can only be used with one worker process, so the \fB\-w 1\fP option is
required. Note that a single gevent worker can handle a large number of
concurrent clients.
.sp
Note: Gevent provides a \fBmonkey_patch()\fP function that replaces all the
blocking functions in the standard library with equivalent asynchronous
versions. While python\-engineio does not require monkey patching, other
libraries such as database drivers are likely to require it.
.SS uWSGI
.sp
When using the uWSGI server in combination with gevent, the Engine.IO server
can take advantage of uWSGI\(aqs native WebSocket support.
.sp
Instances of class \fBengineio.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 asynchoronous mode explicitly, the
\fBasync_mode\fP option can be given in the constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
# gevent with uWSGI
eio = engineio.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 Standard Threads
.sp
While not comparable to eventlet and gevent in terms of performance,
the Engine.IO server can also be configured to work with multi\-threaded web
servers that use standard Python threads. This is an ideal setup to use with
development servers such as \X'tty: link http://werkzeug.pocoo.org'\fI\%Werkzeug\fP\X'tty: link'\&.
.sp
Instances of class \fBengineio.Server\fP will automatically use the threading
mode if neither eventlet nor gevent are not installed. To request the
threading mode explicitly, the \fBasync_mode\fP option can be given in the
constructor:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio = engineio.Server(async_mode=\(aqthreading\(aq)
.EE
.UNINDENT
.UNINDENT
.sp
A server configured for threading is deployed as a regular web application,
using any WSGI complaint multi\-threaded server. The example below deploys an
Engine.IO application combined with a Flask web application, using Flask\(aqs
development web server based on Werkzeug:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
eio = engineio.Server(async_mode=\(aqthreading\(aq)
app = Flask(__name__)
app.wsgi_app = engineio.WSGIApp(eio, app.wsgi_app)

# ... Engine.IO and Flask handler functions ...

if __name__ == \(aq__main__\(aq:
    app.run()
.EE
.UNINDENT
.UNINDENT
.sp
The example that follows shows how to start an Engine.IO application using
Gunicorn\(aqs threaded worker class:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
$ gunicorn \-w 1 \-\-threads 100 module:app
.EE
.UNINDENT
.UNINDENT
.sp
With the above configuration the server will be able to handle up to 100
concurrent clients.
.sp
When using standard threads, WebSocket is supported through the
\X'tty: link https://github.com/miguelgrinberg/simple-websocket'\fI\%simple\-websocket\fP\X'tty: link'
package, which must be installed separately. This package provides a
multi\-threaded WebSocket server that is compatible with Werkzeug and Gunicorn\(aqs
threaded worker. Other multi\-threaded web servers are not supported and will
not enable the WebSocket transport.
.SS Scalability Notes
.sp
Engine.IO is a stateful protocol, which makes horizontal scaling more
difficult. To deploy a cluster of Engine.IO processes hosted on one or
multiple servers the following conditions must be met:
.INDENT 0.0
.IP \(bu 2
Each Engine.IO server process must be able to handle multiple requests
concurrently. This is required 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 process. Load balancers call this \fIsticky sessions\fP, or
\fIsession affinity\fP\&.
.UNINDENT
.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.
.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.
.