Debian Codegraph @

demo/wuclient.r

raw symbols SCIP
1 ### Weather updates client as in the ZeroMQ guide.
2 # SHELL> Rscript wuserver.r &
3 # SHELL> Rscript wuclient.r
4 # SHELL> rm weather.ipc
5
6 suppressMessages(library(pbdZMQ, quietly = TRUE))
7
8 ### Initial.
9 cat("Collecting updates from weather server ...\n");
10 context <- zmq.ctx.new()
11 subscriber <- zmq.socket(context, ZMQ.ST()$SUB)
12 zmq.connect(subscriber, "tcp://localhost:5556")
13
14 ### Ask for four zip codes.
15 filters <- c("50011", "37831", "37996", "20993")
16 for(i in 1:length(filters)){
17 cat("Subscribe zipcode", filters[i], "\n")
18 zmq.setsockopt(subscriber, ZMQ.SO()$SUBSCRIBE, filters[i])
19 }
20
21 ### Process weather updates.
22 N.updates <- 30
23 temperature <- vector(mode = "list", length = 4)
24 while(any(sapply(temperature, length) < N.updates)){
25 string <- zmq.recv(subscriber)
26 msg <- strsplit(string$buf, " ")[[1]] # c(zipcode, temperature, humidity)
27 # cat(msg, "\n")
28 id <- which(msg[1] == filters)
29 temperature[[id]] <- c(temperature[[id]], as.integer(msg[2]))
30
31 if(length(temperature[[id]]) == N.updates){
32 ### No need to unsubscribe but demo the way how to do it.
33 cat("Unsubscribe zipcode", filters[id], "\n", sep = " ");
34 zmq.setsockopt(subscriber, ZMQ.SO()$UNSUBSCRIBE, filters[id])
35 }
36 }
37 avg.temperature <- sapply(temperature, mean)
38
39 ### Print average temperature for asked zip codes.
40 for(i in 1:length(filters)){
41 cat("Average temperature for zipcode", filters[i],
42 "was", avg.temperature[i], "\n")
43 }
44
45 ### Finish.
46 zmq.close(subscriber)
47 zmq.ctx.destroy(context)