server_sent_event v0.2.0 ServerSentEvent
Push updates to Web clients over HTTP or using dedicated server-push protocols.
Messages are sent in the following form, with the text/event-stream
MIME type:
data: This is the first message.
data: This is the second message, it
data: has two lines.
event: custom
data: This message has event type 'custom'.
A living standard is available from WHATWG.
The contents of a server-sent-event are:
type | The type of an event |
lines | The data contents of the event split by line |
id | Value to send in last-event-id header when reconnecting |
retry | Time to wait before retrying connection in milliseconds |
comments | Any lines from original block that were marked as comments |
Link to this section Summary
Functions
Does the event have any data lines
This event stream format’s MIME type is text/event-stream
Parse the next event from text stream, if present
Format an event to be sent as part of a stream
Link to this section Functions
Does the event have any data lines.
An event without any data lines will not trigger any browser events.
This event stream format’s MIME type is text/event-stream
.
Parse the next event from text stream, if present.
Examples
In these examples this module has been aliased to SSE
.
iex> SSE.parse("data: This is the first message\n\n")
{%SSE{lines: ["This is the first message"]}, ""}
iex> SSE.parse("data:First whitespace character is optional\n\n")
{%SSE{lines: ["First whitespace character is optional"]}, ""}
iex> SSE.parse("data: This message\ndata: has two lines.\n\n")
{%SSE{lines: ["This message", "has two lines."]}, ""}
iex> SSE.parse("data: This is the first message\n\nrest")
{%SSE{lines: ["This is the first message"]}, "rest"}
iex> SSE.parse("data: This message is not complete")
nil
iex> SSE.parse("event: custom\ndata: This message is type custom\n\n")
{%SSE{type: "custom", lines: ["This message is type custom"]}, ""}
iex> SSE.parse("id: 100\ndata: This message has an id\n\n")
{%SSE{id: "100", lines: ["This message has an id"]}, ""}
iex> SSE.parse("retry: 5000\ndata: This message retries after 5s.\n\n")
{%SSE{retry: 5000, lines: ["This message retries after 5s."]}, ""}
iex> SSE.parse(": This is a comment\n\n")
{%SSE{comments: ["This is a comment"]}, ""}
iex> SSE.parse("data: data can have more :'s in it'\n\n")
{%SSE{lines: ["data can have more :'s in it'"]}, ""}
Format an event to be sent as part of a stream
NOTE: Each data/comment line must be without new line charachters.
Examples
In these examples this module has been aliased to SSE
.
iex> %SSE{type: "greeting", lines: ["Hi,", "there"], comments: ["comment"]}
...> |> SSE.serialize()
"event: greeting\n: comment\ndata: Hi,\ndata: there\n\n"
iex> %SSE{lines: ["message with id"], id: "some-id"}
...> |> SSE.serialize()
"data: message with id\nid: some-id\n\n"
iex> %SSE{lines: ["message setting retry to 10s"], retry: 10_000}
...> |> SSE.serialize()
"data: message setting retry to 10s\nretry: 10000\n\n"