update readme with some EventSource examples

This commit is contained in:
Me No Dev 2016-06-29 21:58:01 +03:00
parent 330027a8de
commit 5137dbe0bf
1 changed files with 51 additions and 0 deletions

View File

@ -671,6 +671,57 @@ client->binary(flash_binary, 4);
The server includes EventSource (Server-Sent Events) plugin which can be used to send short text events to the browser.
Difference between EventSource and WebSockets is that EventSource is single direction, text-only protocol.
### Setup Event Source on the server
```cpp
AsyncWebServer server(80);
AsyncEventSource events("/events");
void setup(){
// setup ......
events.onConnect([](AsyncEventSourceClient *client){
if(client->lastId()){
Serial.printf("Client reconnected! Last message ID that it gat is: %u\n", client->lastId());
}
//send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!",NULL,millis(),1000);
});
server.addHandler(&events);
// setup ......
}
void loop(){
if(eventTriggered){ // your logic here
//send event "myevent"
client->send("my event content","myevent",millis());
}
}
```
### Setup Event Source in the browser
```javascript
if (!!window.EventSource) {
var source = new EventSource('/events');
source.addEventListener('open', function(e) {
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e) {
if (e.target.readyState != EventSource.OPEN) {
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e) {
console.log("message", e.data);
}, false);
source.addEventListener('myevent', function(e) {
console.log("myevent", e.data);
}, false);
}
```
## Setting up the server
```cpp