Generate a new Elixir project using mix
and add cowboy
and plug
as dependencies in mix.exs
:
defp deps do
[
{:cowboy, "~> 1.0.0"},
{:plug, "~> 0.8.1"}
]
end
Then add the sse.ex
file below to lib/
and run the code with mix run --no-halt lib/sse.ex
. Point your browser to http://localhost:4000
and you're done.
If you don't feel like writing your own EventSource JavaScript, you can use the example in index.html below that comes from Cowboy. Just create a priv/static
directory inside of your project.
Soo I spent a good week implementing this into my system, and THEN it turned out, that browsers limit the number of SSE connections to 6!!! wtf why 6? Why a limit at all? Well, here's more details: https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource
I'm switching to WebSockets.