I'm trying to write the daemon in R such as it would be broadcasting the data to some data pipe and any peer connected to this pipe would get the last value transmitted. I've changed the server code from here, so my server side looks:
server <- function(){
writeLines("Listening...")
con <- socketConnection(host="localhost", port = 6011, blocking=TRUE,
server=TRUE, open="r+")
while(TRUE){
broadcast_msg <- as.character(Sys.time())
writeLines(broadcast_msg, con)
Sys.sleep(1)
}
close(con)
}
server()
On client side i just connect and read the lines:
con <- socketConnection(host="localhost", port = 6011, blocking=TRUE, server=FALSE, open="r+")
server_resp_update <- readLines(con, 1)
server_resp_update <- readLines(con, 1)
server_resp_update <- readLines(con, 1)
The code above has two problems:
- Daemon waits for the peer to connect. However i want it to broadcast the data in any case.
- When i connect and read the data with client several times i get the first lines sent in the beginning after the connection, but not the last up-to-date value.
There was similar question in Python and the answer was to inverse the problem doing:
- Wait for a connection
- Give a message
- go to step 1
In my case 2. Give a message involves heavy calculation and i dont want to do them for every peer's request - i want the daemon to do them once a sec for everyone who needs the message.
I did managed to get this scheme work using a txt file, i.e. the daemon re-writes a new value in the file every second and the client reads the file when it needs to do so. No waiting for peer's involved. However writing/reading file is not as fast as socket connection can be.