session.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package internal
  2. import (
  3. "net"
  4. "one.com/nnet"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. )
  9. const (
  10. // Close Reason builtin
  11. CLOSE_REASON_READ = 1
  12. CLOSE_REASON_WRITE = 2
  13. CLOSE_REASON_PROTOCOL = 4
  14. CLOSE_REASON_READTIMEOUT = 8 // HEARTBEAT
  15. CLOSE_REASON_SERVER_CLOSED = 16 //
  16. )
  17. // 长连接
  18. type Session struct {
  19. id uint64
  20. hub nnet.IHub
  21. conn nnet.IConn
  22. extraData interface{}
  23. once sync.Once // Close once
  24. closed int32 // Flag: session closed or not
  25. frozen int32 // Flag: is session frozen. when no responding, no receiving, but can send.
  26. chClose chan struct{}
  27. chSend chan nnet.IPacket
  28. chRecv chan nnet.IPacket
  29. }
  30. func newSession(conn nnet.IConn, h nnet.IHub) *Session {
  31. return &Session{
  32. hub: h,
  33. conn: conn,
  34. chClose: make(chan struct{}),
  35. chSend: make(chan nnet.IPacket, h.Conf().SizeOfSendChan),
  36. chRecv: make(chan nnet.IPacket, h.Conf().SizeOfRecvChan),
  37. }
  38. }
  39. func (self *Session) GetData() interface{} {
  40. return self.extraData
  41. }
  42. func (self *Session) SetData(data interface{}) {
  43. self.extraData = data
  44. }
  45. func (self *Session) GetRawConn() nnet.IConn {
  46. return self.conn
  47. }
  48. func (self *Session) UpdateId(id uint64) {
  49. self.id = id
  50. self.hub.PutSession(id, self)
  51. }
  52. func (self *Session) Id() uint64 {
  53. return self.id
  54. }
  55. func (self *Session) SetId(id uint64) {
  56. self.id = id
  57. }
  58. func (self *Session) Do() {
  59. suc, reason := self.hub.Callback().OnConnected(self)
  60. if !suc {
  61. //TODO: 这里不 Close 资源能释放吗?
  62. self.Close(reason)
  63. return
  64. }
  65. asyncDo(self.loopHandle, self.hub.Wg())
  66. asyncDo(self.loopWrite, self.hub.Wg())
  67. asyncDo(self.loopRead, self.hub.Wg())
  68. }
  69. func (self *Session) Close(reason int32) {
  70. self.close(reason)
  71. }
  72. func (self *Session) close(reason int32) {
  73. self.once.Do(func() {
  74. atomic.StoreInt32(&self.closed, 1)
  75. close(self.chClose)
  76. close(self.chSend)
  77. close(self.chRecv)
  78. self.conn.Close()
  79. self.hub.DelSession(self.id)
  80. self.hub.Callback().OnClosed(self, reason)
  81. })
  82. }
  83. func (self *Session) SetFrozen(frozen int32) {
  84. atomic.StoreInt32(&self.frozen, frozen)
  85. }
  86. func (self *Session) IsClosed() bool {
  87. return atomic.LoadInt32(&self.closed) != 0
  88. }
  89. func (self *Session) Write(pkt nnet.IPacket, timeout time.Duration) error {
  90. if self.IsClosed() {
  91. return nnet.ErrConnClosing
  92. }
  93. if timeout > 0 {
  94. _ = self.conn.SetWriteDeadline(time.Now().Add(timeout))
  95. }
  96. data, err := self.hub.Protocol().Serialize(pkt)
  97. if err != nil {
  98. return err
  99. }
  100. _, err = self.conn.Write(data)
  101. return err
  102. }
  103. // public 异步写入
  104. func (self *Session) AWrite(pkt nnet.IPacket, timeout time.Duration) (err error) {
  105. if self.IsClosed() {
  106. return nnet.ErrConnClosing
  107. }
  108. defer func() {
  109. if e := recover(); e != nil {
  110. err = nnet.ErrConnClosing
  111. }
  112. }()
  113. if timeout == 0 {
  114. select {
  115. case self.chSend <- pkt:
  116. return nil
  117. default:
  118. return nnet.ErrWriteBlocking
  119. }
  120. } else {
  121. select {
  122. case self.chSend <- pkt:
  123. return nil
  124. case <-self.chClose:
  125. return nnet.ErrConnClosing
  126. case <-time.After(timeout):
  127. return nnet.ErrWriteBlocking
  128. }
  129. }
  130. }
  131. //
  132. func (self *Session) loopRead() {
  133. var reason int32 = 0
  134. defer func() {
  135. self.close(reason)
  136. }()
  137. for {
  138. select {
  139. case <-self.hub.ChQuit():
  140. reason = CLOSE_REASON_SERVER_CLOSED
  141. return
  142. case <-self.chClose:
  143. return
  144. default:
  145. }
  146. if self.hub.Conf().ReadTimeout > 0 {
  147. self.conn.SetReadDeadline(time.Now().Add(self.hub.Conf().ReadTimeout))
  148. }
  149. pkt, err := self.hub.Protocol().ReadPacket(self.conn)
  150. if err != nil {
  151. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  152. reason = CLOSE_REASON_READTIMEOUT
  153. } else if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
  154. reason = CLOSE_REASON_READTIMEOUT
  155. } else {
  156. reason = CLOSE_REASON_READ
  157. }
  158. //
  159. return
  160. }
  161. if self.frozen == 0 {
  162. self.chRecv <- pkt
  163. }
  164. }
  165. }
  166. //
  167. func (self *Session) loopWrite() {
  168. var reason int32 = 0
  169. defer func() {
  170. //fmt.Println(self.id)
  171. self.close(reason)
  172. }()
  173. ticker := time.NewTicker(self.hub.Conf().Tick)
  174. for {
  175. select {
  176. case <-self.hub.ChQuit():
  177. reason = CLOSE_REASON_SERVER_CLOSED
  178. return
  179. case <-self.chClose:
  180. return
  181. case <-ticker.C:
  182. self.hub.Callback().OnHeartbeat(self)
  183. case pkt := <-self.chSend:
  184. if self.IsClosed() {
  185. return
  186. }
  187. data, err := self.hub.Protocol().Serialize(pkt)
  188. if err != nil {
  189. continue
  190. }
  191. _ = self.conn.SetWriteDeadline(time.Now().Add(self.hub.Conf().Timeout))
  192. _, err = self.conn.Write(data)
  193. if err != nil {
  194. reason = CLOSE_REASON_WRITE
  195. return
  196. }
  197. yes, rsn := pkt.ShouldClose()
  198. if yes {
  199. reason = rsn
  200. return
  201. }
  202. }
  203. }
  204. }
  205. //
  206. func (self *Session) loopHandle() {
  207. var reason int32 = 0
  208. defer func() {
  209. self.close(reason)
  210. }()
  211. for {
  212. select {
  213. case <-self.hub.ChQuit():
  214. reason = CLOSE_REASON_SERVER_CLOSED
  215. return
  216. case <-self.chClose:
  217. return
  218. case pkt := <-self.chRecv:
  219. if self.IsClosed() {
  220. return
  221. }
  222. if !self.hub.Callback().OnMessage(self, pkt) {
  223. reason = CLOSE_REASON_PROTOCOL
  224. return
  225. }
  226. }
  227. }
  228. }
  229. func asyncDo(fn func(), wg *sync.WaitGroup) {
  230. wg.Add(1)
  231. go func() {
  232. fn()
  233. wg.Done()
  234. }()
  235. }