'Provide Last-Event-Id to EventSource constructor
Is it possible to set the Last-Event-Id header of an EventSource ? I have a simple chat app that keeps the messages cached. When I connect, I send all the chat since the Last-Event-Id, or all of them if it is not provided.
Since I keep the messages, I figured I might be able to pass the Id to the EventSource constructor to avoid it giving me back all the messages I already have. Is that simply not possible ?
Solution 1:[1]
The EventSource request will only have the Last-Event-Id header if the connection breaks and the client will have to reconnect. You can "force" this reconnection by letting the server break the first connection.
It goes like this:
- Create a connection using EventSource.
- The server receives the request and test if the
Last-Event-Idis a request header.- If the
Last-Event-Idis present:- get the value/id.
- send events from the server according to the id.
- If the
Last-Event-Idis not present:- send an event containing an id (the id that you consider to be the last id).
- make the server break/finish the connection.
- If the
- If the connection is broken by the server the client will try to reconnect with a new request. This time the request will have a
Last-Event-Idheader, and now you jump up to number 2.
The only problem with this approach is the delay caused by the client because it has to make two connections. I haven't tested the delay, but it looks like something around 3-5 seconds between each request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chrwahl |
