forked from funny/link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
120 lines (102 loc) · 2.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
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
package link
import (
"container/list"
"errors"
"net"
"sync"
"sync/atomic"
)
var ErrClosed = errors.New("link.Session closed")
type Session struct {
id uint64
conn net.Conn
encoder Encoder
decoder Decoder
closeChan chan int
closeFlag int32
closeEventMutex sync.Mutex
closeCallbacks *list.List
State interface{}
}
var globalSessionId uint64
func NewSession(conn net.Conn, codecType CodecType) *Session {
session := &Session{
id: atomic.AddUint64(&globalSessionId, 1),
conn: conn,
encoder: codecType.NewEncoder(conn),
decoder: codecType.NewDecoder(conn),
closeCallbacks: list.New(),
}
return session
}
func (session *Session) Id() uint64 { return session.id }
func (session *Session) Conn() net.Conn { return session.conn }
func (session *Session) IsClosed() bool { return atomic.LoadInt32(&session.closeFlag) == 1 }
func (session *Session) Close() {
if atomic.CompareAndSwapInt32(&session.closeFlag, 0, 1) {
session.invokeCloseCallbacks()
if session.closeChan != nil {
close(session.closeChan)
}
session.conn.Close()
if d, ok := session.encoder.(Disposeable); ok {
d.Dispose()
}
if d, ok := session.decoder.(Disposeable); ok {
d.Dispose()
}
}
}
func (session *Session) Receive(msg interface{}) (err error) {
if session.IsClosed() {
return ErrClosed
}
err = session.decoder.Decode(msg)
if err != nil {
session.Close()
}
return
}
func (session *Session) Send(msg interface{}) (err error) {
if session.IsClosed() {
return ErrClosed
}
err = session.encoder.Encode(msg)
if err != nil {
session.Close()
}
return
}
type closeCallback struct {
Handler interface{}
Func func()
}
func (session *Session) AddCloseCallback(handler interface{}, callback func()) {
if session.IsClosed() {
return
}
session.closeEventMutex.Lock()
defer session.closeEventMutex.Unlock()
session.closeCallbacks.PushBack(closeCallback{handler, callback})
}
func (session *Session) RemoveCloseCallback(handler interface{}) {
if session.IsClosed() {
return
}
session.closeEventMutex.Lock()
defer session.closeEventMutex.Unlock()
for i := session.closeCallbacks.Front(); i != nil; i = i.Next() {
if i.Value.(closeCallback).Handler == handler {
session.closeCallbacks.Remove(i)
return
}
}
}
func (session *Session) invokeCloseCallbacks() {
session.closeEventMutex.Lock()
defer session.closeEventMutex.Unlock()
for i := session.closeCallbacks.Front(); i != nil; i = i.Next() {
callback := i.Value.(closeCallback)
callback.Func()
}
}