-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.go
91 lines (77 loc) · 1.56 KB
/
session.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
package util
import (
"sync"
"github.com/fagongzi/goetty"
"github.com/fagongzi/util/task"
)
var (
stopFlag = &struct{}{}
)
// Session session
type Session struct {
ID interface{}
Addr string
resps *task.Queue
conn goetty.IOSession
releaseFunc func(interface{})
stopOnce sync.Once
stopped chan struct{}
}
// NewSession create a client session
func NewSession(conn goetty.IOSession, releaseFunc func(interface{})) *Session {
s := &Session{
ID: conn.ID(),
Addr: conn.RemoteAddr(),
resps: task.New(32),
conn: conn,
releaseFunc: releaseFunc,
stopped: make(chan struct{}),
}
go s.writeLoop()
return s
}
// Close close the client session
func (s *Session) Close() {
s.resps.Put(stopFlag)
<-s.stopped
}
// OnResp receive a response
func (s *Session) OnResp(resp interface{}) {
if s != nil {
s.resps.Put(resp)
} else {
s.releaseResp(resp)
}
}
func (s *Session) doClose() {
s.stopOnce.Do(func() {
s.resps.Dispose()
s.stopped <- struct{}{}
})
}
func (s *Session) releaseResp(resp interface{}) {
if s.releaseFunc != nil && resp != nil {
s.releaseFunc(resp)
}
}
func (s *Session) writeLoop() {
items := make([]interface{}, 16, 16)
for {
n, err := s.resps.Get(16, items)
if nil != err {
log.Fatalf("BUG: can not failed")
}
for i := int64(0); i < n; i++ {
if items[i] == stopFlag {
GetLogger().Infof("session %d[%s] closed",
s.ID,
s.Addr)
s.doClose()
return
}
s.conn.Write(items[i])
s.releaseResp(items[i])
}
s.conn.Flush()
}
}