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.
lol, I'm looking into SSE now and google led me here :)
what are you using these days and why?
edit: This still works in 2020. I have the same problem as victor, but I'll figure it out.
edit2: now I understand victor's frustration. No headers, sending kep-alive events - connection still dies..
edit3: Okay it's because of Cowboy. Fix is to add
protocol_options: [idle_timeout: :infinity]
to cowboy options. Not ideal though. Can't find a way to set route-specific option.I've documented the process in my blog since this shouldn't take more than an hour and it took me 3 days.