forked from pebbe/zmq3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ticlient.go
81 lines (69 loc) · 1.71 KB
/
ticlient.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
//
// Titanic client example.
// Implements client side of http://rfc.zeromq.org/spec:9
package main
import (
"github.com/pebbe/zmq3/examples/mdapi"
"errors"
"fmt"
"os"
"time"
)
// Calls a TSP service
// Returns response if successful (status code 200 OK), else NULL
//
func ServiceCall(session *mdapi.Mdcli, service string, request ...string) (reply []string, err error) {
reply = []string{}
msg, err := session.Send(service, request...)
if err == nil {
switch status := msg[0]; status {
case "200":
reply = msg[1:]
return
case "400":
fmt.Println("E: client fatal error, aborting")
os.Exit(1)
case "500":
fmt.Println("E: server fatal error, aborting")
os.Exit(1)
}
} else {
fmt.Println("E: " + err.Error())
os.Exit(0)
}
err = errors.New("Didn't succeed")
return // Didn't succeed, don't care why not
}
// The main task tests our service call by sending an echo request:
func main() {
var verbose bool
if len(os.Args) > 1 && os.Args[1] == "-v" {
verbose = true
}
session, _ := mdapi.NewMdcli("tcp://localhost:5555", verbose)
// 1. Send 'echo' request to Titanic
reply, err := ServiceCall(session, "titanic.request", "echo", "Hello world")
if err != nil {
fmt.Println(err)
return
}
var uuid string
if err == nil {
uuid = reply[0]
fmt.Println("I: request UUID", uuid)
}
time.Sleep(100 * time.Millisecond)
// 2. Wait until we get a reply
for {
reply, err := ServiceCall(session, "titanic.reply", uuid)
if err == nil {
fmt.Println("Reply:", reply[0])
// 3. Close request
ServiceCall(session, "titanic.close", uuid)
break
} else {
fmt.Println("I: no reply yet, trying again...")
time.Sleep(5 * time.Second) // Try again in 5 seconds
}
}
}