how can send data from ESP8266 to client in "real" real-time
Posted: Mon Dec 13, 2021 12:10 pm
I tried to build a system that send data, like a simple status on/off, from ESP8266 to a webpage via ESP8266WebServer methods.
At the ESP8266 side I had a function named "handleUpdateData" that I used both in server handler declaration with this declaration
and called asynchronously when i got some variation of the status that i would to be check.
In the "handleUpdateData" function i builded the JSON string with "page" variable using the data stream syntax like
and sended it by this instruction
At the webpage side i had this declaration in javascript first
and after that with
OR (without differences)
In both cases, i received data every 5 seconds regulary.
In case of some exception, when ESP8266 side i builded a new send, at the webpage side I had nothing out synch of 5 seconds, despite i used the id in the message frame that was not verified by web browser.
What's wrong?
At the ESP8266 side I had a function named "handleUpdateData" that I used both in server handler declaration with this declaration
Code: Select all
server->on("/updatedata", handleUpdateData);
and called asynchronously when i got some variation of the status that i would to be check.
In the "handleUpdateData" function i builded the JSON string with "page" variable using the data stream syntax like
Code: Select all
id: 12345
data: { "code": "123",
data: "status": "xxxx" }
and sended it by this instruction
Code: Select all
server->send(200, "text/event-stream", page);
At the webpage side i had this declaration in javascript first
Code: Select all
var eventSource = new EventSource("/updatedata");
and after that with
Code: Select all
eventSource.onmessage = function(e) {
debug("onmessage: "+e.data);
}
OR (without differences)
Code: Select all
eventSource.addEventListener("message", function(e) {
debug("received message: "+e.data);
}
In both cases, i received data every 5 seconds regulary.
In case of some exception, when ESP8266 side i builded a new send, at the webpage side I had nothing out synch of 5 seconds, despite i used the id in the message frame that was not verified by web browser.
What's wrong?