Skip to content

Commit

Permalink
🧦 Fix WebSocket issues
Browse files Browse the repository at this point in the history
  • Loading branch information
fonsp committed Apr 30, 2020
1 parent 8ea7082 commit f974ff8
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 45 deletions.
34 changes: 14 additions & 20 deletions assets/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,7 @@ class PlutoConnection {
}

handleMessage(event) {

var onFailure = (e) => {
console.warn("Failed to get updates!")
console.log(e)

this.waitForOnline()
}

try {
const update = JSON.parse(event.data)

event.data.text().then((msg) => JSON.parse(msg)).then((update) => {
const forMe = !(("notebookID" in update) && (update.notebookID != this.notebookID))
if (!forMe) {
console.log("Update message not meant for this notebook")
Expand All @@ -109,9 +99,12 @@ class PlutoConnection {
}

this.onUpdate(update, byMe)
} catch (error) {
onFailure(error)
}
}).catch((ex) => {
console.error("Failed to get updates!", ex)
console.log(event)

this.waitForOnline()
})
}

startSocketConnection(onSucces) {
Expand All @@ -120,8 +113,7 @@ class PlutoConnection {
this.handleMessage(e)
}
this.psocket.onerror = (e) => {
console.error("SOCKET ERROR")
console.log(e)
console.error("SOCKET ERROR", e)

if (this.psocket.readyState != WebSocket.OPEN && this.psocket.readyState != WebSocket.CONNECTING) {
this.waitForOnline()
Expand All @@ -139,7 +131,6 @@ class PlutoConnection {
console.log(e)

this.waitForOnline()
// startSocketConnection(onSucces)
}
this.psocket.onopen = () => {
this.sendreceive("connect", {}).then(u => {
Expand All @@ -157,7 +148,7 @@ class PlutoConnection {
}

tryCloseSocketConnection() {
this.psocket.close()
this.psocket.close(1000, "byebye")
}

initialize(){
Expand Down Expand Up @@ -185,14 +176,17 @@ class PlutoConnection {
this.clientID = this.getUniqueShortID()
this.sentRequests = {}

window.addEventListener("unload", e => {
this.send("disconnect", {})
window.addEventListener("beforeunload", e => {
//this.send("disconnect", {})
this.psocket.onclose = undefined
this.tryCloseSocketConnection()
})
}

fetchPlutoVersions(){
const githubPromise = fetch("https://api.github.com/repos/fonsp/Pluto.jl/releases", {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
Expand Down
23 changes: 10 additions & 13 deletions assets/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,25 +194,22 @@ document.addEventListener("DOMContentLoaded", () => {
// based on https://stackoverflow.com/a/26716182
// to execute all scripts in the output html:
try {
var scripts = Array.prototype.slice.call(outputNode.getElementsByTagName("script"))
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src != "") {
if (!Array.prototype.map.call(document.head.querySelectorAll("script"), s => s.src).includes(scripts[i])) {
var tag = document.createElement("script")
tag.src = scripts[i].src
Array.from(outputNode.querySelectorAll("script")).map((script) => {
if (script.src != "") {
if (!Array.from(document.head.querySelectorAll("script")).map(s => s.src).includes(script)) {
const tag = document.createElement("script")
tag.src = script.src
document.head.appendChild(tag)
}
} else {
var result = Function(scripts[i].innerHTML).bind(outputNode)()
if (!scripts[i].previousElementSibling && !scripts[i].nextElementSibling) {
if (result && result.nodeType === Node.ELEMENT_NODE) {
scripts[i].parentElement.insertBefore(result, scripts[i])
}
const result = Function(script.innerHTML).bind(outputNode)()
if (result && result.nodeType === Node.ELEMENT_NODE) {
script.parentElement.insertBefore(result, script)
}
}
}
})
} catch (err) {
console.error("Couldn't execute all scripts:")
console.error("Couldn't execute script:")
console.error(err)
// TODO: relay to user
// might be wise to wait after adding scripts to head
Expand Down
11 changes: 5 additions & 6 deletions sample/ui.jl
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,18 @@ Try drawing a rectangle in the canvas below 👇 and notice that the `area` vari

# ╔═╡ 7f4b0e1e-7f16-11ea-02d3-7955921a70bd
@bind dims html"""
<canvas id="drawboard" width="200" height="200"></canvas>
<canvas width="200" height="200" style="position: relative"></canvas>
<script>
const canvas = document.querySelector("canvas#drawboard")
// 🐸 `this` is the cell output wrapper - we use it to select elements 🐸 //
const canvas = this.querySelector("canvas")
const ctx = canvas.getContext("2d")
var startX = 80
var startY = 40
function onmove(e){
// 🐸 This is how we send the value back to Julia 🐸 //
// 🐸 We send the value back to Julia 🐸 //
canvas.value = [e.layerX - startX, e.layerY - startY]
canvas.dispatchEvent(new CustomEvent("input"))
Expand All @@ -108,6 +109,7 @@ function onmove(e){
}
canvas.onmousedown = e => {
console.log(e)
startX = e.layerX
startY = e.layerY
canvas.onmousemove = onmove
Expand All @@ -117,9 +119,6 @@ canvas.onmouseup = e => {
canvas.onmousemove = null
}
// To prevent this code block from showing and hiding
canvas.onclick = e => e.stopPropagation()
// Fire a fake mousemoveevent to show something
onmove({layerX: 130, layerY: 160})
Expand Down
20 changes: 14 additions & 6 deletions src/webserver/WebServer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ function flushclient(client::Client)
try
if client.stream !== nothing
if isopen(client.stream)
write(client.stream, serialize_message(next_to_send))
client.stream.frame_type = HTTP.WebSockets.WS_BINARY
write(client.stream, serialize_message(next_to_send) |> codeunits)
else
@info "Client $(client.id) stream closed."
put!(flushtoken, token)
Expand Down Expand Up @@ -117,7 +118,7 @@ const MSG_DELIM = "IUUQ.km jt ejggjdvmu vhi" # riddle me this, Julius
This will start the static HTTP server and a WebSocket server. Pluto Notebooks will be started dynamically (by user input)."""
function run(port = 1234, launchbrowser = false)
serversocket = Sockets.listen(UInt16(port))
@async HTTP.serve(Sockets.localhost, UInt16(port), stream = true, server = serversocket) do http::HTTP.Stream
servertask = @async HTTP.serve(Sockets.localhost, UInt16(port), stream = true, server = serversocket) do http::HTTP.Stream
# messy messy code so that we can use the websocket on the same port as the HTTP server

if HTTP.WebSockets.is_upgrade(http.message)
Expand All @@ -134,6 +135,14 @@ function run(port = 1234, launchbrowser = false)
# For some reason, long (>256*512 bytes) WS messages get split up - `readavailable` only gives the first 256*512
data = ""
while !endswith(data, MSG_DELIM)
if(eof(clientstream))
if data == ""
return
end
@warn "Unexpected eof after" data
data = data * MSG_DELIM
break
end
data = data * String(readavailable(clientstream))
end
JSON.parse(SubString(data, 1:(lastindex(data)-length(MSG_DELIM))))
Expand Down Expand Up @@ -186,9 +195,10 @@ function run(port = 1234, launchbrowser = false)
HTTP.startwrite(http)
write(http, request.response.body)
catch e
if isa(e, HTTP.IOError) || isa(e, ArgumentError)
if isa(e, Base.IOError) || isa(e, ArgumentError)
@warn "Attempted to write to a closed stream at $(request.target)"
else
@show e, typeof(e), fieldnames(e)
rethrow(e)
end
end
Expand All @@ -205,9 +215,7 @@ function run(port = 1234, launchbrowser = false)

# create blocking call:
try
while true
sleep(typemax(UInt64))
end
wait(servertask)
catch e
if isa(e, InterruptException)
println("\n\nClosing Pluto... Restart Julia for a fresh session. \n\nHave a nice day! 🎈")
Expand Down

0 comments on commit f974ff8

Please sign in to comment.