Skip to content

Instantly share code, notes, and snippets.

@SimonDanisch
Created June 6, 2019 20:52
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 SimonDanisch/973ef4abbae6283c47538fe0f9862766 to your computer and use it in GitHub Desktop.
Save SimonDanisch/973ef4abbae6283c47538fe0f9862766 to your computer and use it in GitHub Desktop.
using Sockets
import AssetRegistry
using WebSockets
using WebSockets: is_upgrade, upgrade, writeguarded
using WebSockets: HTTP
using Hyperscript
@tags div script
@tags_noescape style
websocket_connection = Ref{Any}()
function websocket_handler(ws)
websocket_connection[] = ws
while isopen(ws)
data, success = WebSockets.readguarded(ws)
success || break
@show String(data)
end
end
function handler(req)
# response = default_response(req)
# response !== missing && return response
# return serve_assets(req)
return sprint(io-> show(io, MIME"text/html"(), my_app))
end
function wshandler(req, sock)
req.target == "/webio_websocket/" && websocket_handler(sock)
end
baseurl = "127.0.0.1"
http_port = 8081
ws_default = string("ws://", baseurl, ":", http_port, "/webio_websocket/")
server = WebSockets.ServerWS(handler, wshandler)
server_task = @async WebSockets.serve(server, baseurl, http_port, true)
function Base.show(io::IO, ::MIME"application/prs.juno.plotpane+html", x::Hyperscript.Node)
print(io, """
<!doctype html><html><head>
<meta charset="UTF-8"></head>
<meta name="viewport" content="width=device-width, initial-scale=1"><body>
""")
show(io, MIME"text/html"(), x)
print(io, "</body></html>")
end
websocket_script = script("""
(function () {
function tryconnect(url) {
var ws = new WebSocket(url);
ws.onopen = function () {
ws.onmessage = function (evt) {
console.log(evt.data)
eval(evt.data)
ws.send("boi!")
}
}
ws.onclose = function (evt) {
if (evt.code === 1005) {
// TODO handle this!?
//tryconnect(url)
}
}
}
tryconnect($(repr(ws_default)))
})();
""")
my_app = div("hi", websocket_script)
# open browser, go to http://127.0.0.1:8081/
# then after everything connected, talk:
write(websocket_connection[], "console.log('hiiii')")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment