-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
74 lines (65 loc) · 1.45 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
package flyrpc
import (
"io"
"log"
"net"
)
// Client use to connect server.
type Client struct {
// extend with *Context
*Context
}
func Dial(network, address string) (*Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
var protocol Protocol
if network == "tcp" || network == "unix" {
protocol = NewTcpProtocol(conn, false)
} else {
return nil, newError("not support protocol " + network)
}
return newClient(protocol, nil), nil
}
func newTcpClient(conn net.Conn, serializer Serializer) *Client {
protocol := NewTcpProtocol(conn, false)
return newClient(protocol, serializer)
}
// Create new Client instance.
func newClient(protocol Protocol, serializer Serializer) *Client {
if serializer == nil {
serializer = JSON
}
router := NewRouter(serializer)
context := NewContext(protocol, router, 99, serializer)
cli := &Client{
context,
}
go cli.handlePackets()
return cli
}
func (c *Client) SetSerializer(serializer Serializer) {
c.serializer = serializer
c.Router.(*router).serializer = serializer
}
func (c *Client) handlePackets() {
for {
packet, err := c.Protocol.ReadPacket()
if err != nil {
if err != io.EOF {
log.Println("Close on error", err)
}
c.Close()
break
}
go c.emitPacket(packet)
}
}
func (c *Client) OnMessage(code string, handler HandlerFunc) {
c.Router.AddRoute(code, handler)
}
func (c *Client) Close() error {
c.Context.Close()
return c.Protocol.Close()
}