forked from zeromq/goczmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
beacon.go
106 lines (87 loc) · 2.45 KB
/
beacon.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package goczmq
/*
#include "czmq.h"
zactor_t *Beacon_new () {
zactor_t *beacon = zactor_new(zbeacon, NULL); return beacon;
}
*/
import "C"
import (
"strconv"
"unsafe"
)
// Beacon wraps the CZMQ beacon actor. It implements a
// peer-to-peer discovery service for local networks. Beacons
// can broadcast and receive UDPv4 service broadcasts.
type Beacon struct {
zactorT *C.struct__zactor_t
}
// NewBeacon creates a new Beacon instance.
func NewBeacon() *Beacon {
z := &Beacon{}
z.zactorT = C.Beacon_new()
return z
}
// Verbose sets the beacon to log information to stdout.
func (b *Beacon) Verbose() error {
rc := C.zstr_send(unsafe.Pointer(b.zactorT), C.CString("VERBOSE"))
if rc == -1 {
return ErrActorCmd
}
return nil
}
// Configure accepts a port number and configures
// the beacon, returning an address
func (b *Beacon) Configure(port int) (string, error) {
rc := C.zstr_sendm(unsafe.Pointer(b.zactorT), C.CString("CONFIGURE"))
if rc == -1 {
return "", ErrActorCmd
}
rc = C.zstr_send(unsafe.Pointer(b.zactorT), C.CString(strconv.Itoa(port)))
if rc == -1 {
return "", ErrActorCmd
}
Chostname := C.zstr_recv(unsafe.Pointer(b.zactorT))
hostname := C.GoString(Chostname)
return hostname, nil
}
// Publish publishes an announcement at an interval
func (b *Beacon) Publish(announcement string, interval int) error {
rc := C.zstr_sendm(unsafe.Pointer(b.zactorT), C.CString("PUBLISH"))
if rc == -1 {
return ErrActorCmd
}
rc = C.zstr_sendm(unsafe.Pointer(b.zactorT), C.CString(announcement))
if rc == -1 {
return ErrActorCmd
}
rc = C.zstr_send(unsafe.Pointer(b.zactorT),
C.CString(strconv.Itoa(interval)))
if rc == -1 {
return ErrActorCmd
}
return nil
}
// Subscribe subscribes to beacons matching the filter
func (b *Beacon) Subscribe(filter string) error {
rc := C.zstr_sendm(unsafe.Pointer(b.zactorT), C.CString("SUBSCRIBE"))
if rc == -1 {
return ErrActorCmd
}
rc = C.zstr_send(unsafe.Pointer(b.zactorT), C.CString(filter))
if rc == -1 {
return ErrActorCmd
}
return nil
}
// Recv waits for the specific timeout in milliseconds to receive a beacon
func (b *Beacon) Recv(timeout int) [][]byte {
C.zsock_set_rcvtimeo(unsafe.Pointer(b.zactorT), C.int(timeout))
addrStr := C.zstr_recv(unsafe.Pointer(b.zactorT))
beaconStr := C.zstr_recv(unsafe.Pointer(b.zactorT))
return [][]byte{[]byte(C.GoString(addrStr)), []byte(C.GoString(beaconStr))}
}
// Destroy destroys the beacon.
func (b *Beacon) Destroy() {
C.zactor_destroy(&b.zactorT)
}