session.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package internal
  2. import (
  3. "net"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "one.com/nnet"
  8. )
  9. // 关闭原因
  10. const (
  11. // Close Reason 是一个 int32 型数据,这是系统预置的几个代码
  12. CLOSE_REASON_READ = 0
  13. CLOSE_REASON_WRITE = 0
  14. CLOSE_REASON_PROTOCOL = 1
  15. CLOSE_REASON_READTIMEOUT = 4 // HEARTBEAT
  16. CLOSE_REASON_SERVER_CLOSED = 16 // 本服务器关闭
  17. )
  18. // 长连接
  19. type Session struct {
  20. id uint64
  21. hub nnet.IHub
  22. conn nnet.IConn
  23. extraData interface{}
  24. once sync.Once // Close once
  25. closed int32 // session 是否关闭
  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) IsClosed() bool {
  84. return atomic.LoadInt32(&self.closed) != 0
  85. }
  86. func (self *Session) Write(pkt nnet.IPacket, timeout time.Duration) error {
  87. if self.IsClosed() {
  88. return nnet.ErrConnClosing
  89. }
  90. if timeout > 0 {
  91. _ = self.conn.SetWriteDeadline(time.Now().Add(timeout))
  92. }
  93. _, err := self.conn.Write(pkt.Serialize())
  94. return err
  95. }
  96. // public 异步写入
  97. func (self *Session) AWrite(pkt nnet.IPacket, timeout time.Duration) (err error) {
  98. if self.IsClosed() {
  99. return nnet.ErrConnClosing
  100. }
  101. defer func() {
  102. if e := recover(); e != nil {
  103. err = nnet.ErrConnClosing
  104. }
  105. }()
  106. if timeout == 0 {
  107. select {
  108. case self.chSend <- pkt:
  109. return nil
  110. default:
  111. return nnet.ErrWriteBlocking
  112. }
  113. } else {
  114. select {
  115. case self.chSend <- pkt:
  116. return nil
  117. case <-self.chClose:
  118. return nnet.ErrConnClosing
  119. case <-time.After(timeout):
  120. return nnet.ErrWriteBlocking
  121. }
  122. }
  123. }
  124. // 循环从 socket 读取数据,置入 chRecv 通道
  125. func (self *Session) loopRead() {
  126. var reason int32 = 0
  127. defer func() {
  128. self.close(reason)
  129. }()
  130. for {
  131. select {
  132. case <-self.hub.ChQuit():
  133. reason = CLOSE_REASON_SERVER_CLOSED
  134. return
  135. case <-self.chClose:
  136. return
  137. default:
  138. }
  139. if self.hub.Conf().ReadTimeout > 0 {
  140. self.conn.SetReadDeadline(time.Now().Add(self.hub.Conf().ReadTimeout))
  141. }
  142. pkt, err := self.hub.Protocol().ReadPacket(self.conn)
  143. if err != nil {
  144. if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
  145. reason = CLOSE_REASON_READTIMEOUT
  146. } else if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
  147. reason = CLOSE_REASON_READTIMEOUT
  148. } else {
  149. reason = CLOSE_REASON_READ
  150. }
  151. //
  152. return
  153. }
  154. self.chRecv <- pkt
  155. }
  156. }
  157. // 循环从 cbSend 通道读取数据,发送到 socket
  158. func (self *Session) loopWrite() {
  159. var reason int32 = 0
  160. defer func() {
  161. //fmt.Println(self.id)
  162. self.close(reason)
  163. }()
  164. ticker := time.NewTicker(self.hub.Conf().Tick)
  165. for {
  166. select {
  167. case <-self.hub.ChQuit():
  168. reason = CLOSE_REASON_SERVER_CLOSED
  169. return
  170. case <-self.chClose:
  171. return
  172. case <-ticker.C:
  173. self.hub.Callback().OnHeartbeat(self)
  174. case pkt := <-self.chSend:
  175. if self.IsClosed() {
  176. return
  177. }
  178. data := pkt.Serialize()
  179. defer pkt.Destroy(data)
  180. _ = self.conn.SetWriteDeadline(time.Now().Add(self.hub.Conf().Timeout))
  181. _, err := self.conn.Write(data)
  182. if err != nil {
  183. reason = CLOSE_REASON_WRITE
  184. return
  185. }
  186. yes, rsn := pkt.ShouldClose()
  187. if yes {
  188. reason = rsn
  189. return
  190. }
  191. }
  192. }
  193. }
  194. // 循环从 chRecv 读取解析好的数据,回调到实现层
  195. func (self *Session) loopHandle() {
  196. var reason int32 = 0
  197. defer func() {
  198. self.close(reason)
  199. }()
  200. for {
  201. select {
  202. case <-self.hub.ChQuit():
  203. reason = CLOSE_REASON_SERVER_CLOSED
  204. return
  205. case <-self.chClose:
  206. return
  207. case pkt := <-self.chRecv:
  208. if self.IsClosed() {
  209. return
  210. }
  211. if !self.hub.Callback().OnMessage(self, pkt) {
  212. reason = CLOSE_REASON_PROTOCOL
  213. return
  214. }
  215. }
  216. }
  217. }
  218. func asyncDo(fn func(), wg *sync.WaitGroup) {
  219. wg.Add(1)
  220. go func() {
  221. fn()
  222. wg.Done()
  223. }()
  224. }