@@ -224,6 +224,43 @@ You can specify wheter the redirect is permanent or temporary by passing ``perma
224
224
:emphasize-lines: 14-18,26,38
225
225
:linenos:
226
226
227
+ Server-Sent Events
228
+ ------------------
229
+
230
+ All types of responses until now were synchronous, meaning that the response was sent immediately after the handler function returned.
231
+ However, sometimes you might want to send data to the client at a later time, e.g. when some event occurs.
232
+ This can be overcomed by periodically polling the server, but it is not an elegant solution. Instead, you can use Server-Sent Events (SSE).
233
+
234
+ Response is initialized on ``return``, events can be sent using ``.send_event()`` method. Due to the nature of SSE, it is necessary to store the
235
+ response object somewhere, so that it can be accessed later.
236
+
237
+ **Because of the limited number of concurrently open sockets, it is not possible to process more than one SSE response at the same time.
238
+ This might change in the future, but for now, it is recommended to use SSE only with one client at a time.**
239
+
240
+ .. literalinclude:: ../examples/httpserver_sse.py
241
+ :caption: examples/httpserver_sse.py
242
+ :emphasize-lines: 10,17,44-51,61
243
+ :linenos:
244
+
245
+ Websockets
246
+ ----------
247
+
248
+ Although SSE provide a simple way to send data from the server to the client, they are not suitable for sending data the other way around.
249
+
250
+ For that purpose, you can use Websockets. They are more complex than SSE, but they provide a persistent two-way communication channel between
251
+ the client and the server.
252
+
253
+ Remember, that because Websockets also receive data, you have to explicitly call ``.receive()`` on the ``Websocket`` object to get the message.
254
+ This is anologous to calling ``.poll()`` on the ``Server`` object.
255
+
256
+ **Because of the limited number of concurrently open sockets, it is not possible to process more than one Websocket response at the same time.
257
+ This might change in the future, but for now, it is recommended to use Websocket only with one client at a time.**
258
+
259
+ .. literalinclude:: ../examples/httpserver_websocket.py
260
+ :caption: examples/httpserver_websocket.py
261
+ :emphasize-lines: 10,16-17,60-67,76,81
262
+ :linenos:
263
+
227
264
Multiple servers
228
265
----------------
229
266
0 commit comments