Debian Codegraph @

R/socket.R

raw
1
2 # avoid R CMD check errors with older R
3 if (getRversion() < "4.0") {
4 utils::globalVariables(c("serverSocket", "socketAccept"))
5 }
6
7 renv_socket_server <- function(min = 49152, max = 65535) {
8
9 # create the socket server
10 socket <- NULL
11 for (i in 1:2000) {
12 port <- sample(min:max, size = 1L)
13 socket <- catch(serverSocket(port))
14 if (inherits(socket, "error"))
15 socket <- NULL
16 else
17 break
18 }
19
20 # if we still don't have a socket here, we failed
21 if (is.null(socket))
22 stop("error creating socket server: couldn't find open port")
23
24 # return information about the server
25 list(
26 socket = socket,
27 port = port,
28 pid = Sys.getpid()
29 )
30
31 }
32
33 renv_socket_connect <- function(port, open, timeout = getOption("timeout")) {
34
35 socketConnection(
36 host = "127.0.0.1",
37 port = port,
38 open = open,
39 blocking = TRUE,
40 encoding = "native.enc",
41 timeout = timeout
42 )
43
44 }
45
46 renv_socket_accept <- function(socket, open, timeout = getOption("timeout")) {
47
48 # socketAccept() blocks indefinitely on many platforms regardless
49 # of the timeout parameter; poll with socketSelect() first to
50 # enforce the timeout reliably
51 ready <- socketSelect(list(socket), write = FALSE, timeout = timeout)
52 if (!ready)
53 stop("socket accept timed out")
54
55 socketAccept(
56 socket = socket,
57 open = open,
58 blocking = TRUE,
59 encoding = "native.enc",
60 timeout = timeout
61 )
62
63 }