This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
89 lines (69 loc) · 2.04 KB
/
client.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
package main
import (
"flag"
"fmt"
"log"
"time"
wwr "github.com/qbeon/webwire-go"
wwrclt "github.com/qbeon/webwire-go/client"
)
// EchoClient implements the wwrclt.Implementation interface
type EchoClient struct {
connection *wwrclt.Client
}
// NewEchoClient constructs and returns a new echo client instance
func NewEchoClient(serverAddr string) *EchoClient {
newEchoClient := &EchoClient{}
// Initialize connection
newEchoClient.connection = wwrclt.NewClient(
serverAddr,
newEchoClient,
wwrclt.Options{
// Default timeout for timed requests
DefaultRequestTimeout: 10 * time.Second,
ReconnectionInterval: 2 * time.Second,
},
)
return newEchoClient
}
// OnDisconnected implements the wwrclt.Implementation interface
func (clt *EchoClient) OnDisconnected() {}
// OnSessionClosed implements the wwrclt.Implementation interface
func (clt *EchoClient) OnSessionClosed() {}
// OnSessionCreated implements the wwrclt.Implementation interface
func (clt *EchoClient) OnSessionCreated(_ *wwr.Session) {}
// OnSignal implements the wwrclt.Implementation interface
func (clt *EchoClient) OnSignal(_ wwr.Payload) {}
// Request sends a message to the server and returns the reply.
// panics if the request fails for whatever reason
func (clt *EchoClient) Request(message string) wwr.Payload {
// Define a payload to be sent to the server, use default binary encoding
payload := wwr.Payload{
Data: []byte(message),
}
log.Printf(
"Sent request: '%s' (%d)",
string(payload.Data),
len(payload.Data),
)
// Send request and await reply
reply, err := clt.connection.Request("", payload)
if err != nil {
panic(fmt.Errorf("Request failed: %s", err))
}
return reply
}
var serverAddr = flag.String("addr", ":8081", "server address")
func main() {
// Parse command line arguments
flag.Parse()
// Initialize a new echo client instance
echoClient := NewEchoClient(*serverAddr)
// Send request and await reply
reply := echoClient.Request("hey, server!")
log.Printf(
"Received reply: '%s' (%d)",
string(reply.Data),
len(reply.Data),
)
}