WebIO Counter

using WebIO
using HTTP
using WebSockets
using Sockets
using Mux
using Base64
using WebIO
using JSExpr
using JSON

Code to have Mux bind at 0.0.0.0 (and not default localhost).

1.0s
using WebSockets
import WebSockets.serve, WebSockets.ServerWS
import HTTP.HandlerFunction

struct WebSockConnection <: WebIO.AbstractConnection
    sock
end

function create_socket(req)
    sock = req[:socket]
    conn = WebSockConnection(sock)

    t = @async while isopen(sock)
        data = read(sock)

        msg = JSON.parse(String(data))
        WebIO.dispatch(conn, msg)
    end

    wait(t)
end

mk_response(d) = d
function mk_response(d::Dict)
  r = HTTP.Response(get(d, :status, 200))
  haskey(d, :body) && (r.body = d[:body])
  haskey(d, :headers) && (r.headers = d[:headers])
  return r
end

function http_handler(app)
  handler = HandlerFunction((req) -> mk_response(app.warez(req)))
  # handler.events["error"]  = (client, error) -> println(error)
  # handler.events["listen"] = (port)          -> println("Listening on $port...")
  return handler
end

function ws_handler(app)
  handler = WebSockets.WebsocketHandler((req, client) -> mk_response(app.warez((req, client))))
  return handler
end

function webio_serve2(app, addr, port)
    http = Mux.App(Mux.mux(
        Mux.defaults,
        app,
        Mux.notfound()
    ))

    websock = Mux.App(Mux.mux(
        Mux.wdefaults,
        Mux.route("/webio-socket", create_socket),
        Mux.wclose,
        Mux.notfound(),
    ))
		ws_server = ServerWS(http_handler(http), ws_handler(websock))
    serve(ws_server, addr, port, true)
end
2.4s
function counter(start=0)
    scope = Scope()
  	# js init code
  	stringmime("text/html", scope)	
  
    # updates to this update the UI
    count = Observable(scope, "count", start)

    onjs(count, # listen on JavaScript
         JSExpr.@js x->this.dom.querySelector("#count").textContent = x)

    on(count) do n # listen on Julia
      println("GotSomething")  
      println(n > 0 ? "+"^n : "-"^abs(n))
    end

    btn(label, d) = dom"button"(
        label,
        events=Dict(
            "click" => JSExpr.@js () -> $count[] = $count[] + $d
        )
    )

    scope.dom = dom"div"(
        btn("increment", 1),
        btn("decrement", -1),
        dom"div#count"(string(count[])),
    )

    scope
end
c = counter(1)
nothing
app = page("/", req -> c)
@async webio_serve2(app, "0.0.0.0", 9998)
sleep(60)
© 2018 Nextjournal GmbH