forked from booksbyus/zguide
/
wuclient.flx
56 lines (46 loc) · 1.67 KB
/
wuclient.flx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Weather update client
// Connects SUB socket to tcp://localhost:5556
// Collects weather updates and finds avg temp in zipcode
//
open ZeroMQ;
fun parse_int(s:string,var i:int) = {
var acc = 0;
while s.[i] \in "0123456789" do
acc = acc * 10 + s.[i].ord - "0".char.ord;
++i;
done
return i,acc;
}
fun parse_space(s:string, i:int)=> i+1;
fun parse_weather(s:string) = {
var i = 0;
def i, val zipcode = parse_int (s,i);
i = parse_space(s,i);
def i, val temperature = parse_int (s,i);
i = parse_space(s,i);
def i, val relhumidity= parse_int (s,i);
return zipcode, temperature, relhumidity;
}
var context = zmq_init 1;
// Socket to talk to server
println "Collecting updates from weather server...";
var subscriber = context.mk_socket ZMQ_SUB;
zmq_validate$ subscriber.connect "tcp://localhost:5556";
// Subscribe to zipcode 100
filter := if System::argc > 1 then System::argv 1 else "1001" endif;
zmq_validate$ subscriber.set_sockopt$ zmq_subscribe filter;
// Process 100 updates
var total_temp = 0;
for var update_nbr in 0 upto 99 do
e,s := subscriber.recv_string;
zmq_validate$ e;
zipcode, temperature, relhumidity := parse_weather s;
total_temp += temperature;
done
println$
f"Average temperature for zipcode '%S' was %d C\n"$
filter, total_temp / update_nbr
;
zmq_validate$ subscriber.close;
zmq_validate$ context.term;