-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
67 lines (52 loc) · 1.07 KB
/
tcp.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
package tcp
import (
"io"
"net"
"strings"
"sync"
"golang.org/x/net/context"
"github.com/o8x/jk/v2/crash"
"github.com/o8x/jk/v2/logger"
)
func WritePacket(addr string, packet []byte) (int, error) {
d, err := net.Dial("tcp", addr)
if err != nil {
return 0, err
}
defer d.Close()
return d.Write(packet)
}
func ListenAndServe(ctx context.Context, addr string, fn func(net.Conn, error)) error {
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
logger.Info("tcp server listen on tcp://%s", l.Addr())
w := sync.WaitGroup{}
go func() {
defer crash.Recover("crashed by tcp listen")
for {
conn, err := l.Accept()
if err == io.EOF {
logger.Info("tcp server EOF")
return
}
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
logger.Info("tcp server closed")
return
}
}
w.Add(1)
go func(c net.Conn, err error) {
defer w.Done()
defer crash.Recover("crashed by tcp accept")
fn(c, err)
}(conn, err)
}
}()
<-ctx.Done()
err = l.Close()
w.Wait()
return err
}