WebSockets¶
Introduction¶
WebSockets are a technology that allows real-time bidirectional communication between a client (such as a web browser) and a server. This is done through a single persistent socket connection, which reduces latency and improves efficiency in applications that need frequent updates, such as live chats, online games, or real-time dashboards.
Cafeto uses the same WebSockets from Starlette for real-time communication and offers two ways to implement it.
Traditional Method¶
| Python | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
In this case, the information is received as JSON without being assigned to a DTO, and the response is a JSON with the format:
| JSON | |
|---|---|
1 2 3 4 | |
Callback Method¶
| Python | |
|---|---|
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 | |
| Python | |
|---|---|
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 | |
Note: It is important to note that the response should not be made using
ModelResponsebutModelWSResponse. For now, responses like JSONResponse, PlainTextResponse, and HTMLResponse are not available with WebSockets.
It is also possible to do it this way:
| Python | |
|---|---|
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 | |
| Python | |
|---|---|
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 | |
In this method, messages arrive in a DTO, with all the validations and features that DTOs imply in HTTP actions.
The response also changes, as WebSocket messages do not have a statusCode like traditional HTTP requests. The incoming message would have the following format:
| JSON | |
|---|---|
1 2 3 4 5 6 7 | |
But if the DTO validations fail, the response could be:
| JSON | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 | |
In this way, the response of HTTP requests can be emulated.
Note: Only the
on_receivecallback is required;on_connectandon_disconnectare optional.