Some Websocket servers require a ping to be sent at a specified interval (e.g. every 60 seconds) to keep the connection alive.
As the WebSocket object from the websocket
package is not exportable, it cannot be loaded into a background session.
Is there any workaround to send a ping without blocking the main process?
For example:
library(websocket)
ws <- websocket::WebSocket$new("ws://websockets.chilkat.io/wsChilkatEcho.ashx", autoConnect = TRUE)
ws$onMessage(function(event) {
cat(Sys.time(), "Server response:", event$data, "\n")
})
ws$send("Hello world!")
# This code doesn't work - it blocks the main process and stops onMessage from receiving messages
while(TRUE) {
Sys.sleep(60)
ws$send("Ping")
}
# This code doesn't work - it throws an error, as the ws object cannot be loaded into a new process
callr::r_bg(function(ws) {
Sys.sleep(60)
ws$send("Ping")
}, args = list(ws))