-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
73 lines (60 loc) · 1.29 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
64
65
66
67
68
69
70
71
72
73
package packetize
import (
"context"
"errors"
"net"
"time"
)
type Listener struct {
listener net.Listener
connChan chan *Conn
closeCtx context.Context
close context.CancelFunc
}
func Listen(network string, addr string) (*Listener, error) {
listener, err := net.Listen(network, addr)
if err != nil {
return nil, err
}
closeCtx, closeFunc := context.WithCancel(context.Background())
lst := &Listener{
listener: listener,
connChan: make(chan *Conn),
closeCtx: closeCtx,
close: closeFunc,
}
go func() {
for lst.closeCtx.Err() == nil {
conn, err := lst.listener.Accept()
if err != nil {
continue
}
cloneCtx, closeFunc := context.WithCancel(context.Background())
pkConn := &Conn{
conn: conn,
readDeadline: make(chan time.Time),
packetChan: make(chan []byte, 32),
closeCtx: cloneCtx,
close: closeFunc,
}
go pkConn.process()
lst.connChan <- pkConn
}
}()
return lst, nil
}
func (lst *Listener) Accept() (net.Conn, error) {
select {
case conn := <-lst.connChan:
return conn, nil
case <-lst.closeCtx.Done():
return nil, errors.New("accept: listener closed")
}
}
func (lst *Listener) Close() error {
lst.close()
return lst.listener.Close()
}
func (lst *Listener) Addr() net.Addr {
return lst.listener.Addr()
}