-
Notifications
You must be signed in to change notification settings - Fork 384
/
api.go
86 lines (76 loc) · 1.86 KB
/
api.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
package link
import (
"io"
"net"
"strings"
"time"
)
type Protocol interface {
NewCodec(rw io.ReadWriter) (Codec, error)
}
type ProtocolFunc func(rw io.ReadWriter) (Codec, error)
func (pf ProtocolFunc) NewCodec(rw io.ReadWriter) (Codec, error) {
return pf(rw)
}
type Codec interface {
Receive() (interface{}, error)
Send(interface{}) error
Close() error
}
type ClearSendChan interface {
ClearSendChan(<-chan interface{})
}
func Listen(network, address string, protocol Protocol, sendChanSize int, handler Handler) (*Server, error) {
listener, err := net.Listen(network, address)
if err != nil {
return nil, err
}
return NewServer(listener, protocol, sendChanSize, handler), nil
}
func Dial(network, address string, protocol Protocol, sendChanSize int) (*Session, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
codec, err := protocol.NewCodec(conn)
if err != nil {
return nil, err
}
return NewSession(codec, sendChanSize), nil
}
func DialTimeout(network, address string, timeout time.Duration, protocol Protocol, sendChanSize int) (*Session, error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return nil, err
}
codec, err := protocol.NewCodec(conn)
if err != nil {
return nil, err
}
return NewSession(codec, sendChanSize), nil
}
func Accept(listener net.Listener) (net.Conn, error) {
var tempDelay time.Duration
for {
conn, err := listener.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
if strings.Contains(err.Error(), "use of closed network connection") {
return nil, io.EOF
}
return nil, err
}
return conn, nil
}
}