Created
June 5, 2019 22:48
-
-
Save alandipert/4001aead0f102fa18773889329a1a16a to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env Rscript | |
app <- list( | |
call = function(req) { | |
list( | |
status = 200L, | |
headers = list('Content-Type' = 'text/html'), | |
body = ' | |
<html> | |
<head><title>websocket test</title></head> | |
<body> | |
<script type="text/javascript"> | |
window.addEventListener("DOMContentLoaded", (event) => { | |
const ws = new WebSocket(window.location.toString().replace(/^http/, "ws")); | |
ws.addEventListener("open", function (event) { | |
ws.send("Hello Server!"); | |
}); | |
ws.addEventListener("message", function (event) { | |
const txt = document.createTextNode(`Message from server: ${event.data}`), | |
p = document.createElement("p"); | |
p.appendChild(txt); | |
document.body.appendChild(p); | |
}); | |
}); | |
</script> | |
<h1>oh, hello</h1> | |
</body> | |
</html> | |
' | |
) | |
}, | |
onWSOpen = function(wsServer) { | |
cat("wsServer opened\n") | |
wsClient <- websocket::WebSocket$new("ws://echo.websocket.org") | |
# Problematic because could send messages out of order? | |
retrySend <- function(msg) { | |
if (wsClient$readyState() == 0L) { | |
later::later(~retrySend(msg)) | |
} else wsClient$send(msg) | |
} | |
wsServer$onMessage(function(isBinary, msgFromClient) { | |
retrySend(msgFromClient) | |
}) | |
wsServer$onClose(function() { | |
cat("wsServer closed\n") | |
wsClient$close() | |
}) | |
wsClient$onMessage(function(e) { | |
wsServer$send(e$data) | |
}) | |
wsClient$onClose(function(e) { | |
cat("wsClient closed\n") | |
}) | |
} | |
) | |
httpuv::startServer("0.0.0.0", 4434, app) | |
while(TRUE) later::run_now() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment