ServerSentEvent library for parsing and consuming as a Client

Push updates to web clients over HTTP, using dedicated server-push protocol.

Server Sent Events are a way to push updates to web clients, including browsers. See the spec for more details.

This project includes the tools for manipulating, serializing and parsing Events in this format.
It can be used to build both clients and servers.

Event Client

This library now also includes an Elixir Client for an event stream.
The client behaviour defines callbacks that handle connection/disconnect/reconnect and incoming events.

A simple client that always connects could be defined as follows

defmodule AutoConnect do
  @behaviour ServerSentEvent.Client

  # Start connecting to the endpoint as soon as client is started.
  def init(state) do
    {:connect, request(state), state}

  # The client has successfully connected, or reconnected, to the event stream.
  def handle_connect(_response, state) do
    {:noreply, state}

  # Retry connecting to endpoint 1 second after a failure to connect.
  def handle_connect_failure(reason, state) do
    {:connect, request(state), state}

  # Immediatly try to reconnect when the connection is lost.
  def handle_disconnect(_, state) do
    {:connect, request(state), state}

  # Update the running state of the client with the id of each event as it arrives.
  # This event id is used for reconnection.
  def handle_event(event, state) do
    IO.puts("I just got a new event: #{inspect(event)}")
    %{state | last_event_id:}

  # When stop message is received this process will exit with reason :normal.
  def handle_info(:stop, state) do
    {:stop, :normal, state}

  # Not a callback but helpful pattern for creating requests in several callbacks
  defp request({url: url}) do
    Raxx.request(:GET, url)
    |> Raxx.set_header("accept", "text/event-stream")
    |> Raxx.set_header("last-event-id", state.last_event_id)

# Starting the client
{:ok, pid} = AutoConnect.start_link(%{url: "", last_event_id: "0"})

The client can also be added to a supervision tree

children = [
  {AutoConnect, %{url: "", last_event_id: "0"}}

Is just me, or maybe you forgot to link the project @Crowdhailer ? ^^

1 Like

Fixed, thanks

Is there any javascript to go with this, so it could be used from a browser?

There is already a browser API for consuming ServerSentEvents.

The fact this API exists is the main reason I use them.

Now I get it, thanks

1 Like

0.4.3 Fixes connection edgecases in the ServerSentEvent.Client

See CHANGELOG for details

1 Like

0.4.7 Make parsing 2_000x faster.

Just that.

See issue for benchmark and discussions.


0.4.8 Add support for raxx 0.18.0

No breaking changes in this version of raxx affect this library so it now supports 0.16.x, 0.17.x and 0.18.x versions of raxx

1 Like

1.0.0 released

Removes support for pre-stable versions of Raxx when using the ServerSentEvent.Client.

1 Like