forked from pebbe/zmq4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udpping2.go
62 lines (49 loc) · 1.14 KB
/
udpping2.go
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
56
57
58
59
60
61
62
//
// UDP ping command
// Model 2, uses the GO net library
//
// this doesn't use ZeroMQ at all
package main
import (
"fmt"
"log"
"net"
"time"
)
const (
PING_PORT_NUMBER = 9999
PING_MSG_SIZE = 1
PING_INTERVAL = 1000 * time.Millisecond // Once per second
)
func main() {
log.SetFlags(log.Lshortfile)
// Create UDP socket
bcast := &net.UDPAddr{Port: PING_PORT_NUMBER, IP: net.IPv4bcast}
conn, err := net.ListenUDP("udp", bcast)
if err != nil {
log.Fatalln(err)
}
buffer := make([]byte, PING_MSG_SIZE)
// We send a beacon once a second, and we collect and report
// beacons that come in from other nodes:
// Send first ping right away
ping_at := time.Now()
for {
if err := conn.SetReadDeadline(ping_at); err != nil {
log.Fatalln(err)
}
if _, addr, err := conn.ReadFrom(buffer); err == nil {
// Someone answered our ping
fmt.Println("Found peer", addr)
}
if time.Now().After(ping_at) {
// Broadcast our beacon
fmt.Println("Pinging peers...")
buffer[0] = '!'
if _, err := conn.WriteTo(buffer, bcast); err != nil {
log.Fatalln(err)
}
ping_at = time.Now().Add(PING_INTERVAL)
}
}
}