forked from st3v/go-plugins
/
listener.go
63 lines (53 loc) · 1.05 KB
/
listener.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
package utp
import (
"bufio"
"encoding/gob"
"net"
"time"
"github.com/micro/go-log"
"github.com/micro/go-micro/transport"
)
func (u *utpListener) Addr() string {
return u.l.Addr().String()
}
func (u *utpListener) Close() error {
return u.l.Close()
}
func (u *utpListener) Accept(fn func(transport.Socket)) error {
var tempDelay time.Duration
for {
c, err := u.l.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
}
log.Logf("utp: Accept error: %v; retrying in %v\n", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return err
}
encBuf := bufio.NewWriter(c)
sock := &utpSocket{
timeout: u.t,
conn: c,
encBuf: encBuf,
enc: gob.NewEncoder(encBuf),
dec: gob.NewDecoder(c),
}
go func() {
defer func() {
if r := recover(); r != nil {
sock.Close()
}
}()
fn(sock)
}()
}
}