1 // (c) Bernhard Tittelbach, 2013
6 zmq "github.com/vaughan0/go-zmq"
11 // ---------- ZeroMQ Code -------------
13 func ZmqsInit(sub_connect_port, sub_listen_port, pub_port, keylookup_port string) (ctx *zmq.Context, sub_chans *zmq.Channels, pub_sock *zmq.Socket, keylookup_sock *zmq.Socket) {
15 ctx, err = zmq.NewContext()
19 //close only on later panic, otherwise leave open:
20 defer func(){ if r:= recover(); r != nil { ctx.Close(); panic(r) } }()
22 if len(sub_connect_port) > 0 && len(sub_listen_port) > 0 {
23 sub_sock, err := ctx.Socket(zmq.Sub)
27 defer func() { if r:= recover(); r != nil { sub_sock.Close(); panic(r) } }()
29 sub_sock.Subscribe([]byte{}) //subscribe empty filter -> aka to all messages
31 if err = sub_sock.Bind(sub_listen_port); err != nil {
35 if err = sub_sock.Connect(sub_connect_port); err != nil {
39 sub_chans = sub_sock.ChannelsBuffer(10)
40 go zmqsHandleError(sub_chans)
45 if len(pub_port) > 0 {
46 pub_sock, err = ctx.Socket(zmq.Pub)
50 defer func() { if r:= recover(); r != nil { pub_sock.Close(); panic(r) } }()
52 if err = pub_sock.Bind(pub_port); err != nil {
59 if len(keylookup_port) > 0 {
60 keylookup_sock, err = ctx.Socket(zmq.Req)
64 defer func() { if r:= recover(); r != nil { keylookup_sock.Close(); panic(r) } }()
66 if err = keylookup_sock.Connect(keylookup_port); err != nil {
76 func zmqsHandleError(chans *zmq.Channels) {
77 for error := range(chans.Errors()) {
83 func ZmqsBindNewReplySocket(ctx *zmq.Context, addr string) (chans *zmq.Channels, err error) {
85 return nil, errors.New("No listen address given")
87 sock, err := ctx.Socket(zmq.Rep)
88 if err != nil { return nil, err}
90 if err = sock.Bind(addr); err != nil {
95 chans = sock.ChannelsBuffer(10)
96 go zmqsHandleError(chans)
101 func ZmqsRequestAnswer(sock *zmq.Socket, request [][]byte) (answer [][]byte) {
102 if err := sock.Send(request); err != nil {
105 parts, err := sock.Recv()
112 func ZmqsAskQuestionsAndClose(ctx *zmq.Context, addr string, questions [][][]byte) [][][]byte {
113 if len(addr) == 0 || ctx == nil { return nil }
115 req_sock, err := ctx.Socket(zmq.Req)
119 defer req_sock.Close()
121 if err = req_sock.Connect(addr); err != nil {
125 rv := make([][][]byte, len(questions))
126 for index, q := range(questions) {
127 rv[index] = ZmqsRequestAnswer(req_sock, q)
132 func LookupCardIdNick(s *zmq.Socket, hexbytes []byte) (string, error) {
133 answ := ZmqsRequestAnswer(s, [][]byte{hexbytes})
135 return "", errors.New("Empty reply received")
137 if bytes.Compare(answ[0], []byte("ERROR")) == 0 {
138 return "", errors.New(string(bytes.Join(answ[1:],[]byte(" "))))
140 if bytes.Compare(answ[0], []byte("RESULT")) != 0 || len(answ) != 3{
141 return "", errors.New("Unknown reply received")
143 if bytes.Compare(answ[1], hexbytes) != 0 {
144 return "", errors.New("Wrong reply received")
146 return string(answ[2]), nil