-
Notifications
You must be signed in to change notification settings - Fork 5
/
connection.go
109 lines (87 loc) · 1.52 KB
/
connection.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
package conn
import (
"net"
"os"
"sync"
"sync/atomic"
"time"
"github.com/hb-go/conn/pkg/log"
"github.com/neverhook/easygo/netpoll"
)
var (
connPool sync.Pool
poolCount int64
)
type Conn struct {
id int64
conn net.Conn
file *os.File //copy of origin connection fd
desc *netpoll.Desc
reading int32
closed int32
timestamp time.Time
}
func init() {
connPool = sync.Pool{
New: func() interface{} {
poolCount++
c := Conn{
id: poolCount,
}
return &c
},
}
}
func getConnection(conn net.Conn) *Conn {
c := connPool.Get().(*Conn)
c.conn = conn
c.closed = 0
return c
}
func (c *Conn) closeAndPut() {
c.close()
c.put()
}
func (c *Conn) put() {
c.reset()
connPool.Put(c)
}
func (c *Conn) reset() {
c.conn = nil
c.file = nil
c.desc = nil
c.closed = 0
c.reading = 0
}
// set closed flag,conn.Close()
func (c *Conn) close() {
doit := atomic.CompareAndSwapInt32(&c.closed, 0, 1)
if !doit {
// 关闭一个已关闭的Connection
return
}
if c.conn != nil {
if err := c.conn.Close(); err != nil {
log.Errorf("conn close error:%v", err)
}
}
// close copied fd
if c.file != nil {
if err := c.file.Close(); err != nil {
log.Errorf("conn file close error:%v", err)
}
}
return
}
func (c *Conn) isClosed() bool {
return c.closed > 0
}
func (c *Conn) setReading() bool {
return atomic.CompareAndSwapInt32(&c.reading, 0, 1)
}
func (c *Conn) setReaded() bool {
return atomic.CompareAndSwapInt32(&c.reading, 1, 0)
}
func (c *Conn) isReading() bool {
return c.reading > 0
}