1//
2//  UDP ping command
3//  Model 2, uses the GO net library
4//
5
6//  this doesn't use ZeroMQ at all
7
8package main
9
10import (
11	"fmt"
12	"log"
13	"net"
14	"time"
15)
16
17const (
18	PING_PORT_NUMBER = 9999
19	PING_MSG_SIZE    = 1
20	PING_INTERVAL    = 1000 * time.Millisecond //  Once per second
21)
22
23func main() {
24
25	log.SetFlags(log.Lshortfile)
26
27	//  Create UDP socket
28	bcast := &net.UDPAddr{Port: PING_PORT_NUMBER, IP: net.IPv4bcast}
29	conn, err := net.ListenUDP("udp", bcast)
30	if err != nil {
31		log.Fatalln(err)
32	}
33
34	buffer := make([]byte, PING_MSG_SIZE)
35
36	//  We send a beacon once a second, and we collect and report
37	//  beacons that come in from other nodes:
38
39	//  Send first ping right away
40	ping_at := time.Now()
41
42	for {
43		if err := conn.SetReadDeadline(ping_at); err != nil {
44			log.Fatalln(err)
45		}
46
47		if _, addr, err := conn.ReadFrom(buffer); err == nil {
48			//  Someone answered our ping
49			fmt.Println("Found peer", addr)
50		}
51
52		if time.Now().After(ping_at) {
53			//  Broadcast our beacon
54			fmt.Println("Pinging peers...")
55			buffer[0] = '!'
56			if _, err := conn.WriteTo(buffer, bcast); err != nil {
57				log.Fatalln(err)
58			}
59			ping_at = time.Now().Add(PING_INTERVAL)
60		}
61	}
62}
63