This is VERY simple R function that when ran turns your R session into a websocket server. For this example it returns the standard deviation from a JSON encoded array sent via websockets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #Connect to this using websockets on port 9454 #Send in the format of {"data":[1,2,3]} #The ppp returns the standard deviation of the sent array library(jsonlite) library(httpuv) #server app <- list( onWSOpen = function(ws) { ws$onMessage(function(binary, message) { write(message, file = "log.txt",append = TRUE, sep = "\n") message <- fromJSON(message) ws$send(toJSON(sd(message$data))) }) } ) runServer("0.0.0.0", 9454, app, 250) |
This method can be used to do all sorts of things, include return information for the R workspace environment and even dynamically run code through the use of eval() on your global environment (not recommended for security reasons). If you want to respond with the workspace environment information simply swap out ws$send() with the following…
1 2 | ws$send(toJSON(ls(envir = .GlobalEnv))) |
Hope this is useful for someone. I will be putting together a much more involved tutorial sometime down the road that will cover dashboards outside the use of Shiny.
Be First to Comment