channels
Last updated
Last updated
Let’s first look at what synchronous and asynchronous work is in terms of Django.
Django works synchronously. That is, an HTTP request is handled completely synchronously. A request is sent, waited and the response is returned.
The server is not able to send a single message to the client. In a synchronous operation, there should be a request to get a response.
In asynchronous operation, we launch a request. There is no waiting for a response, the app continues to serve the user and executes the tasks.
Websockets is a protocol that can establish two-way communication between the browser and the server (HTTP is a one-way protocol). A client can send a message to a server and receive a message about the relevant event without having to wait for a response. Both parties can communicate with each other independently at the same time.
Websocket is a stateful protocol, meaning the connection between client and server stays alive until terminated by one of the parties (client or server). After closing the connection by either client or server, the connection is terminated from both ends.
In the first step, the client sends an HTTP request to the server. It asks the server to open a WebSocket connection. The server accepts it and returns a 101 switching protocols response. At this point, the handshake is completed. TCP/IP connection is left open and both sides can send messages. The connection remains open until one of them drops off. This process is often referred to as full-duplex.
When a client sends an HTTP request, it is received by a Django application via WSGI (web server gateway interface). It ends up in Django’s URL and is routed to Django’s view.
For WebSockets, ASGI (asynchronous server gateway interface) is in charge instead of WSGI. And it is routed to a consumer instead of a view.