WebSocket Communication between R Server and Chrome Client




Complete example showing how to: 1. Set up a WebSocket server in R 2. Continuously collect data from a URL 3. Process the data and store results in a dataframe 4. Send the data to a Chrome client 5. Display the data as a chart in the browser

R Server Side Code

library(websocket) library(httr) library(jsonlite) # Create a dataframe to store results results_df <- data.frame( timestamp = character(), value = numeric(), stringsAsFactors = FALSE ) # Function to fetch and process data from URL fetch_data <- function() { # Example: Fetch random data from an API # Replace with your actual data source response <- GET("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd") data <- content(response, "parsed") # Process the data current_time <- format(Sys.time(), "%Y-%m-%d %H:%M:%S") value <- data$bitcoin$usd # Add to dataframe new_row <- data.frame(timestamp = current_time, value = value) results_df <<- rbind(results_df, new_row) # Keep only last 100 entries if (nrow(results_df) > 100) { results_df <<- tail(results_df, 100) } # Return latest data point list(timestamp = current_time, value = value, all_data = results_df) } # WebSocket server start_websocket_server <- function() { ws_server <- WebSocket$new("127.0.0.1", 8080) ws_server$onConnection(function(ws) { cat("Client connected\n") # Send initial data data <- fetch_data() ws$send(toJSON(data)) # Set up a timer to send updates every 2 seconds timer <- later::later( function() { if (ws$readyState() == 1) { # 1 = OPEN data <- fetch_data() ws$send(toJSON(data)) timer <<- later::later(repeatable, 2) } }, 2 ) repeatable <- function() { if (ws$readyState() == 1) { data <- fetch_data() ws$send(toJSON(data)) timer <<- later::later(repeatable, 2) } } ws$onClose(function() { cat("Client disconnected\n") if (!is.null(timer)) later::destroy(timer) }) }) cat("WebSocket server running on ws://127.0.0.1:8080\n") later::run_now() } # Start the server start_websocket_server()

Chrome Client Side Code (HTML/JavaScript)

How to Run This Example

1. Save the R code to a file (e.g., `websocket_server.R`) 2. Run the R script: `Rscript websocket_server.R` 3. Save the HTML code to `client.html` 4. Open `client.html` in Chrome 5. You should see a real-time chart updating every 2 seconds with data from the R server

Key Features

1. R Server Side: - Uses `websocket` package to create a WebSocket server - Fetches data from a URL (Bitcoin price API in this example) - Stores historical data in a dataframe - Sends both latest data point and all historical data to client 2. Chrome Client Side: - Connects to the R server via WebSocket - Uses Chart.js to visualize the data - Updates the chart in real-time as new data arrives You can modify the `fetch_data()` function to collect data from any URL or API you need. The example shows Bitcoin prices, but you can replace it with any data source.