roblabla
roblabla

Reputation: 123

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 ?

Upvotes: 3

Views: 3308

Answers (2)

chrwahl
chrwahl

Reputation: 13135

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:

  1. Create a connection using EventSource.
  2. The server receives the request and test if the Last-Event-Id is a request header.
    • If the Last-Event-Id is present:
      • get the value/id.
      • send events from the server according to the id.
    • If the Last-Event-Id is 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.
  3. 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-Id header, 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.

Upvotes: 1

baynezy
baynezy

Reputation: 7066

You can pass information on the query string.

var source = EventSource("source?eventId=12345");

Ultimately it is just up to you to make sense of it on the server side and return the correct event(s).

Upvotes: 2

Related Questions