1//
2//  Weather update client.
3//  Connects SUB socket to tcp://localhost:5556
4//  Collects weather updates and finds avg temp in zipcode
5//
6
7package main
8
9import (
10	zmq "github.com/pebbe/zmq4"
11
12	"fmt"
13	"os"
14	"strconv"
15	"strings"
16)
17
18func main() {
19	//  Socket to talk to server
20	fmt.Println("Collecting updates from weather server...")
21	subscriber, _ := zmq.NewSocket(zmq.SUB)
22	defer subscriber.Close()
23	subscriber.Connect("tcp://localhost:5556")
24
25	//  Subscribe to zipcode, default is NYC, 10001
26	filter := "10001 "
27	if len(os.Args) > 1 {
28		filter = os.Args[1] + " "
29	}
30	subscriber.SetSubscribe(filter)
31
32	//  Process 100 updates
33	total_temp := 0
34	update_nbr := 0
35	for update_nbr < 100 {
36		msg, _ := subscriber.Recv(0)
37
38		if msgs := strings.Fields(msg); len(msgs) > 1 {
39			if temperature, err := strconv.Atoi(msgs[1]); err == nil {
40				total_temp += temperature
41				update_nbr++
42			}
43		}
44	}
45	fmt.Printf("Average temperature for zipcode '%s' was %dF \n\n", strings.TrimSpace(filter), total_temp/update_nbr)
46}
47