-
Notifications
You must be signed in to change notification settings - Fork 35
/
tls_conn.go
125 lines (102 loc) · 1.82 KB
/
tls_conn.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"net"
"sync"
"github.com/polevpn/elog"
)
const (
CH_TCP_WRITE_SIZE = 2000
)
type TLSConn struct {
conn net.Conn
wch chan []byte
closed bool
handler *RequestHandler
wg *sync.WaitGroup
}
func NewTLSConn(conn net.Conn, handler *RequestHandler) *TLSConn {
return &TLSConn{
conn: conn,
closed: false,
wch: make(chan []byte, CH_TCP_WRITE_SIZE),
handler: handler,
wg: &sync.WaitGroup{},
}
}
func (kc *TLSConn) Close(flag bool) error {
if !kc.closed {
kc.closed = true
if kc.wch != nil {
kc.wch <- nil
close(kc.wch)
}
err := kc.conn.Close()
if flag {
go kc.handler.OnClosed(kc, false)
}
kc.wg.Wait()
return err
}
return nil
}
func (kc *TLSConn) String() string {
return kc.conn.RemoteAddr().String() + "->" + kc.conn.LocalAddr().String()
}
func (kc *TLSConn) IsClosed() bool {
return kc.closed
}
func (kc *TLSConn) StartProcess() {
kc.wg.Add(2)
go kc.read()
go kc.write()
}
func (kc *TLSConn) read() {
defer func() {
kc.wg.Done()
kc.Close(true)
}()
defer PanicHandler()
for {
pkt, err := ReadPacket(kc.conn)
if err != nil {
elog.Error(kc.String(), " read packet end status=", err)
return
}
kc.handler.OnRequest(pkt, kc)
}
}
func (kc *TLSConn) write() {
defer func() {
kc.wg.Done()
kc.Close(true)
}()
defer PanicHandler()
for {
pkt, ok := <-kc.wch
if !ok {
elog.Error(kc.String(), ",channel closed")
return
}
if pkt == nil {
elog.Info(kc.String(), ",exit write process")
return
}
_, err := kc.conn.Write(pkt)
if err != nil {
elog.Error(kc.String(), ",conn write packet end status=", err)
return
}
}
}
func (kc *TLSConn) Send(pkt []byte) {
if kc.closed {
return
}
if kc.wch != nil {
select {
case kc.wch <- pkt:
default:
elog.Error(kc.String(), " wch is full")
}
}
}