Skip to content

Instantly share code, notes, and snippets.

@m-j-w
Created April 22, 2017 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-j-w/27c3696dca320cb4cbdfc5f50152735b to your computer and use it in GitHub Desktop.
Save m-j-w/27c3696dca320cb4cbdfc5f50152735b to your computer and use it in GitHub Desktop.
HTTP5 Server Sent Event in Julia
# Example adapted from https://www.html5rocks.com/en/tutorials/eventsource/basics/WebSockets.jl
using HttpServer
hdr = Dict{AbstractString,AbstractString}(
[ "Content-Type" => "text/event-stream"
, "Cache-Control" => "no-cache"
, "Connection" => "keep-alive" ] )
idx = raw"""
<html><body><h1>Getting server updates</h1><div id="result"></div><script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/push/");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script></body></html>
"""
http = HttpHandler() do req::Request, res::Response
if ismatch(r"^/push/", req.resource)
println("Serving Push...")
Response( 200, hdr,
#"event: update\n" * # Give this event a name to be filtered
# or handled accordingly on the client side
#"id: myid\n" * # Give this update a unique id, e.g. from local time
#"retry: 10000\n" * # Retry reconnect every 10s = 10_000 ms
"data: The server time is: $(now())\n\n" )
else
println("Serving Index...")
Response(idx)
end
end
http.events["error"] = (client, err) -> println(err)
http.events["listen"] = (port) -> println("Listening on $port...")
http.events["connect"] = (client) -> println("$(client.id) connected.")
http.events["close"] = (client) -> println("$(client.id) closed.")
server = Server(http)
try
host = IPv4(127,0,0,1)
run(server, host=host, port=1234)
catch e
println('\n',e,'\n')
end
close(server)
@hustf
Copy link

hustf commented Apr 22, 2017

Hi, I'm not an expert, but my experience from using HttpServer is that sockets close after some minutes, or when you switch to a different browser pane. It may be possible to store a tcpsocket reference, and then connect to it from another process. But Websockets are made for this, and they're supported directly by HttpServer and Websockets.

@m-j-w
Copy link
Author

m-j-w commented Apr 23, 2017

@hustf Thanks for the hint!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment