As mentioned in the previous chapter a lot of Web applications use the ordinary "client - server" communication model and polling technique. In this mode the Web client is always the initiator of transactions, requesting data from the server. Thus, there are no mechanism for the server to independently send data to the client without the client first making a request.
"HTTP Long polling" method
A certain modification of the polling mechanism is the "long polling" method. This technique is an optimisation of the ordinary polling method. Sometimes this method is also considered to emulate internet push technology.
In HTTP long polling method the client application sends a request and "patiently" waits. The net connection is open.
For example, the IoT device sends data to the server and waits for a command.
The serwer will receive data and it doesn't respond immadiately. It will send nothing until it has something to send. Note that the answer will close the network connection. We don't want this. For example, the server will only send a reply when it has a new command to execute on the IoT device. This new command may be caused by some event (e.g. it could be a message from another client).
Timing diagram of events in the "Long polling" mechanism.
This algorithm can be summarized as follows:
1. The client sends a request to the server.
2. The server doesn’t close the connection until it has a data to send.
The server tries to hold a client’s connection open for as long as possible (until a timeout expires). Only the occurrence of a specific event reduces the connection opening time.
3. When the event appears – the server responds to the request of the client.
4. The client sends a new request immediately.
Examples of the implementation of the method described here can be found in my service in the gadgets section. Take a look there virtual devices such as "Network-controlled RGB lamp 01" lamp or "ESP8266 module - 02".
The advantage of the HTTP long polling method is that the commands are passed almost in real time from the server to the IoT devices. So the long polling method can be a substitute for real-time communication. The network traffic is relatively less than with the polling method.
However, the using of the long polling method is very risky. Imagine that a client sending a request and waiting. During this waiting the connection "client - server" will broken. In this situation, the client can wait indefinitely. This problem should be solved if you want to use this method.
Recommended sources and utilities:
• Internet of Things