9 con <- cons[[rdy[j]]]
10 # read client request
11 req <- unserialize(con)
Againserialize()andunserialize()are good enough here to read the
short message from the client indicating what kind of operation—typically
reading a shared variable or writing one—it’s requesting. But the reads
and writes of the shared variables themselves use the fasterreadBin()and
writeBin()functions. Here’s the write part:
# write data dt, of mode md (integer of double), to connection cn
binwrite <- function(dt,md,cn) {
writeBin(dt,con=cn)
And here’s the read part:
# read sz elements of mode md (integer of double) from connection cn
binread <- function(cn,md,sz) {
return(readBin(con=cn,what=md,n=sz))
On the client side, the connection setup code is as follows:
1 options("timeout"=10000)
2 # connect to server
3 con <- socketConnection(host=host,port=port,blocking=TRUE,open="a+b")
4 serialize(list(req="checking in"),con)
5 # receive this client's ID and total number of clients from server
6 myidandnclnt <- unserialize(con)
7 myinfo <<-
8 list(con=con,myid=myidandnclnt[1],nclnt=myidandnclnt[2])
The code for reading from and writing to the server is similar to the pre-
ceding server examples.
250 Chapter 10