Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.