/
tcp4Listener.go
64 lines (47 loc) · 1.05 KB
/
tcp4Listener.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
package connection
import (
"net"
"sync"
watermillnet "github.com/andyollylarkin/watermill-net"
)
type TCP4Listener struct {
l net.Listener
conn watermillnet.Connection
mu sync.Mutex
}
func NewTCP4Listener(addr string) (*TCP4Listener, error) {
tl := new(TCP4Listener)
l, err := net.Listen("tcp4", addr)
if err != nil {
return nil, err
}
tl.l = l
return tl, nil
}
// Accept waits for and returns the next connection to the listener.
func (tl *TCP4Listener) Accept() (watermillnet.Connection, error) {
tl.mu.Lock()
defer tl.mu.Unlock()
conn, err := tl.l.Accept()
if err != nil {
return nil, err
}
t4c := &TCP4Connection{
underlyingConn: conn,
}
tl.conn = t4c
return t4c, nil
}
// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
func (tl *TCP4Listener) Close() error {
tl.mu.Lock()
defer tl.mu.Unlock()
return tl.l.Close()
}
// Addr returns the listener's network address.
func (tl *TCP4Listener) Addr() net.Addr {
tl.mu.Lock()
defer tl.mu.Unlock()
return tl.l.Addr()
}