Skip to content
Prev 7556 / 12125 Next

[R-pkg-devel] socketConnection, delay when reading from

On 11/27/21 8:05 PM, Tomas Kalibera wrote:
This is an extended demo with socketSelect() used to wait on the client 
for some data to be available, to avoid consuming too much CPU by 
polling. To be pasted into two R sessions running on the same computer.
You would have to replace the function done() with something figuring 
out from the data whether it is complete or not, based on the protocol.

Best
Tomas


# the client

con2 <- socketConnection("localhost", port = 6011, open = "rb")
cat("Connected...\n")
total <- 0

done <- function(n) {
 ? n >= 2e8
}

while(!done(total)) {
 ?? cat("Waiting for data to become ready...\n")
 ?? socketSelect(list(con2))
 ?? cat("Reading data...\n")
 ?? r <- readBin(con2, "raw", 1024)
 ?? total <- total + length(r)
 ?? cat("Read", length(r), "bytes (total ", total, ").\n")
}
close(con2)

# the server

n <- 1e8
w <- as.raw(runif(n, 0, 255))
con1 <- socketConnection(port = 6011, blocking = TRUE, server = TRUE, 
open="a+b")
cat("Connected...\n")
writeBin(w, con1)
cat("Sent data the first time, sleeping...\n")
Sys.sleep(10)
cat("Sending data the second time...\n")
writeBin(w, con1)
cat("Data sent to client...\n")
close(con1)