-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
54 lines (42 loc) · 781 Bytes
/
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
package main
import (
"encoding/json"
"math/rand"
"strconv"
"github.com/gorilla/websocket"
)
type ReqCb func(res ResJson)
type ReqCbs map[string]ReqCb
type Client struct {
ws *websocket.Conn
cbs ReqCbs
}
func makeClient() *Client {
result := new(Client)
result.cbs = make(ReqCbs)
return result
}
func (c *Client) connect(urlStr string) error {
ws, _, err := websocket.DefaultDialer.Dial(urlStr, nil)
if err != nil {
return err
}
c.ws = ws
return nil
}
func (c *Client) sendReq(reqType string, rmsg json.RawMessage, cb ReqCb) error {
Id := reqType +
":" +
strconv.Itoa(len(c.cbs)) +
":" +
strconv.Itoa(rand.Int())
if cb != nil {
c.cbs[Id] = cb
}
resJson := ReqJson{
Id: Id,
Type: reqType,
Msg: rmsg,
}
c.ws.WriteJSON(resJson)
}