Load some libraries

library(Rserve)
library(RSclient)
library(ps)
library(dplyr)

Start RServe

Rserve(args = "--vanilla")
## Starting Rserve:
##  /usr/local/Cellar/r/3.6.2/lib/R/bin/R CMD /usr/local/Cellar/r/3.6.2/lib/R/library/Rserve/libs//Rserve --vanilla

Open a connection to the server.

conn <- RSconnect()

There are now two Rserve processes, the top one belongs to our session, the bottom one is the server

processes <- filter(ps(), name == "Rserve")
processes

Now detach the session and note the port number it is listening on

session <- RSdetach(conn)
session$port
## [1] 40190

List the connections that the session’s process is listening on. It is listening (lport) on the port our session will use to reconnect

handle <- ps_handle(processes$pid[[1]])
ps_connections(handle)

Now reattach the session and check the ports again. It is still listening on the session port.

conn <- RSattach(session)
ps_connections(handle)

If you re-attach and detach a couple more times, it keeps listening on all of the session ports.

for (count in 1:10) {
  session <- RSdetach(conn)
  print(session$port)
  conn <- RSattach(session)
}
## [1] 57524
## [1] 37894
## [1] 51555
## [1] 63527
## [1] 57233
## [1] 47181
## [1] 33803
## [1] 33162
## [1] 33403
## [1] 37612
ps_connections(handle)

Stop the server.

RSshutdown(conn)