Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.