Created
April 22, 2017 16:26
-
-
Save m-j-w/27c3696dca320cb4cbdfc5f50152735b to your computer and use it in GitHub Desktop.
HTTP5 Server Sent Event in Julia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.