-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
73 lines (65 loc) · 1.37 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
package emux
import (
"context"
"io"
"sync"
)
type Client struct {
idPool *idPool
onceStart sync.Once
*session
}
func NewClient(ctx context.Context, stm io.ReadWriteCloser, instruction *Instruction) *Client {
return &Client{
session: newSession(ctx, stm, instruction),
}
}
func (c *Client) start() {
c.idPool = newIDPool()
c.init()
go c.handleLoop(nil, c.handleConnected)
}
func (c *Client) Dial(ctx context.Context) (io.ReadWriteCloser, error) {
c.onceStart.Do(c.start)
if c.IsClear() {
return nil, ErrClosed
}
wc := c.dailStream()
if wc == nil {
return nil, errNoFreeStreamID
}
err := wc.connect(ctx)
if err != nil {
return nil, err
}
return wc, nil
}
func (c *Client) dailStream() *stream {
sid := c.idPool.Get()
if sid == 0 {
return nil
}
return c.newStream(sid, c.idPool, true)
}
func (c *Client) handleConnected(cmd uint8, sid uint64) error {
if c.IsClosed() {
return ErrClosed
}
stm := c.getStream(sid)
if stm == nil {
err := errUnknownStreamID
if c.Logger != nil {
c.Logger.Println("emux: handle connected: get stream", "cmd", c.instruction.Info(cmd), "sid", sid, "err", err)
}
return err
}
if stm.isReady() {
err := errStreamIsAlreadyReady
if c.Logger != nil {
c.Logger.Println("emux: handle connected: ready", "cmd", c.instruction.Info(cmd), "sid", sid, "err", err)
}
return err
}
close(stm.ready)
return nil
}