forked from plgd-dev/go-coap
-
Notifications
You must be signed in to change notification settings - Fork 2
/
session.go
134 lines (116 loc) · 2.46 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package udp
import (
"context"
"fmt"
"net"
"sync"
"sync/atomic"
coapNet "github.com/matrix-org/go-coap/v2/net"
"github.com/matrix-org/go-coap/v2/udp/client"
"github.com/matrix-org/go-coap/v2/udp/message/pool"
)
type EventFunc = func()
type Session struct {
connection *coapNet.UDPConn
raddr *net.UDPAddr
maxMessageSize int
closeSocket bool
mutex sync.Mutex
onClose []EventFunc
cancel context.CancelFunc
ctx atomic.Value
}
func NewSession(
ctx context.Context,
connection *coapNet.UDPConn,
raddr *net.UDPAddr,
maxMessageSize int,
closeSocket bool,
) *Session {
ctx, cancel := context.WithCancel(ctx)
s := &Session{
cancel: cancel,
connection: connection,
raddr: raddr,
maxMessageSize: maxMessageSize,
closeSocket: closeSocket,
}
s.ctx.Store(&ctx)
return s
}
// SetContextValue stores the value associated with key to context of connection.
func (s *Session) SetContextValue(key interface{}, val interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
ctx := context.WithValue(s.Context(), key, val)
s.ctx.Store(&ctx)
}
func (s *Session) Done() <-chan struct{} {
return s.Context().Done()
}
func (s *Session) AddOnClose(f EventFunc) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.onClose = append(s.onClose, f)
}
func (s *Session) popOnClose() []EventFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
tmp := s.onClose
s.onClose = nil
return tmp
}
func (s *Session) close() error {
for _, f := range s.popOnClose() {
f()
}
if s.closeSocket {
return s.connection.Close()
}
return nil
}
func (s *Session) Close() error {
s.cancel()
return nil
}
func (s *Session) Context() context.Context {
return *s.ctx.Load().(*context.Context)
}
func (s *Session) WriteMessage(req *pool.Message) error {
data, err := req.Marshal()
if err != nil {
return fmt.Errorf("cannot marshal: %w", err)
}
return s.connection.WriteWithContext(req.Context(), s.raddr, data)
}
func (s *Session) Run(cc *client.ClientConn) (err error) {
defer func() {
err1 := s.Close()
if err == nil {
err = err1
}
err1 = s.close()
if err == nil {
err = err1
}
}()
m := make([]byte, s.maxMessageSize)
for {
buf := m
n, _, err := s.connection.ReadWithContext(s.Context(), buf)
if err != nil {
return err
}
buf = buf[:n]
err = cc.Process(buf)
if err != nil {
return err
}
}
}
func (s *Session) MaxMessageSize() int {
return s.maxMessageSize
}
func (s *Session) RemoteAddr() net.Addr {
return s.raddr
}