-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsocket.go
More file actions
88 lines (78 loc) · 1.5 KB
/
socket.go
File metadata and controls
88 lines (78 loc) · 1.5 KB
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
package libbitcoin
import (
zmq "github.com/pebbe/zmq4"
)
type ZMQSocket struct {
socket *zmq.Socket
socketType zmq.Type
callback chan Response
publicKey string
secretKey string
}
type Response struct {
data []byte
more bool
}
func NewSocket(cb chan Response, socketType zmq.Type) *ZMQSocket {
pub, secret, _ := zmq.NewCurveKeypair()
socket := ZMQSocket{
socketType: socketType,
publicKey: pub,
secretKey: secret,
callback: cb,
}
return &socket
}
func (s *ZMQSocket) Connect(address, publicKey string) error {
sock, err := zmq.NewSocket(s.socketType)
if err != nil {
return err
}
if publicKey != "" {
sock.SetCurvePublickey(s.publicKey)
sock.SetCurveSecretkey(s.secretKey)
sock.SetCurveServerkey(publicKey)
}
if s.socketType == zmq.SUB {
sock.SetSubscribe("")
}
err = sock.Connect(address)
s.socket = sock
if err != nil {
return err
}
go s.poll()
return nil
}
func (s *ZMQSocket) poll() {
for {
b, err := s.socket.RecvBytes(0)
if err != nil {
break
}
more, err := s.socket.GetRcvmore()
if err != nil {
break
}
if len(b) > 0 {
r := Response{
data: b,
more: more,
}
s.callback <- r
}
}
}
func (s *ZMQSocket) Send(data []byte, flag zmq.Flag) {
s.socket.SendBytes(data, flag)
}
func (s *ZMQSocket) Close() {
s.socket.Close()
}
func (s *ZMQSocket) ChangeEndpoint(current, newUrl, newPublicKey string){
s.socket.Disconnect(current)
s.socket.Connect(newUrl)
if newPublicKey != "" {
s.socket.SetCurveServerkey(newPublicKey)
}
}