I have set up a simple httpuv WebSocket server which can receive messages from a WebSocket client and echo them back upon receipt.
For example:
library(httpuv)
s <- startServer("0.0.0.0", 8080,
list(
onWSOpen = function(ws) {
ws$onMessage(function(binary, message) {
ws$send(message)
})
})
)
Is it possible to send messages to that WebSocket client outside of the ws$onMessage
callback?
As an example of how I'd imagine the syntax to be structured, I'd like to be able to call: s$ws$send("Hello")
and have Hello
be sent to the client, without requiring a client message/use of any callback function.
To answer my own question, I have since discovered this is possible using the super assignment operator in R:
library(httpuv)
w <- NULL
s <- startServer("0.0.0.0", 8080,
list(
onWSOpen = function(ws) {
w <<- ws # Now, the WebSocket object persists in the global environment
ws$onMessage(function(binary, message) {
ws$send(message)
})
})
)
# Wait for client to connect...
w$send("Hello") # Send message to the client