mux.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package mux
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/cnlh/nps/lib/common"
  6. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  7. "math"
  8. "net"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. )
  13. type Mux struct {
  14. net.Listener
  15. conn net.Conn
  16. connMap *connMap
  17. newConnCh chan *conn
  18. id int32
  19. closeChan chan struct{}
  20. IsClose bool
  21. pingOk int
  22. connType string
  23. writeQueue chan *bytes.Buffer
  24. sync.Mutex
  25. }
  26. func NewMux(c net.Conn, connType string) *Mux {
  27. m := &Mux{
  28. conn: c,
  29. connMap: NewConnMap(),
  30. id: 0,
  31. closeChan: make(chan struct{}),
  32. newConnCh: make(chan *conn),
  33. IsClose: false,
  34. connType: connType,
  35. writeQueue: make(chan *bytes.Buffer, 20),
  36. }
  37. //read session by flag
  38. go m.readSession()
  39. //ping
  40. go m.ping()
  41. go m.writeSession()
  42. return m
  43. }
  44. func (s *Mux) NewConn() (*conn, error) {
  45. if s.IsClose {
  46. return nil, errors.New("the mux has closed")
  47. }
  48. conn := NewConn(s.getId(), s)
  49. //it must be set before send
  50. s.connMap.Set(conn.connId, conn)
  51. s.sendInfo(common.MUX_NEW_CONN, conn.connId, nil)
  52. logs.Warn("send mux new conn ", conn.connId)
  53. //set a timer timeout 30 second
  54. timer := time.NewTimer(time.Minute * 2)
  55. defer timer.Stop()
  56. select {
  57. case <-conn.connStatusOkCh:
  58. return conn, nil
  59. case <-conn.connStatusFailCh:
  60. case <-timer.C:
  61. }
  62. return nil, errors.New("create connection fail,the server refused the connection")
  63. }
  64. func (s *Mux) Accept() (net.Conn, error) {
  65. if s.IsClose {
  66. return nil, errors.New("accpet error,the mux has closed")
  67. }
  68. conn := <-s.newConnCh
  69. if conn == nil {
  70. return nil, errors.New("accpet error,the conn has closed")
  71. }
  72. return conn, nil
  73. }
  74. func (s *Mux) Addr() net.Addr {
  75. return s.conn.LocalAddr()
  76. }
  77. func (s *Mux) sendInfo(flag uint8, id int32, data interface{}) {
  78. var err error
  79. if flag == common.MUX_NEW_MSG {
  80. if len(data.([]byte)) == 0 {
  81. logs.Warn("send info content is nil")
  82. }
  83. }
  84. buf := common.BuffPool.Get()
  85. //defer pool.BuffPool.Put(buf)
  86. pack := common.MuxPack.Get()
  87. defer common.MuxPack.Put(pack)
  88. err = pack.NewPac(flag, id, data)
  89. if err != nil {
  90. logs.Warn("new pack err", err)
  91. common.BuffPool.Put(buf)
  92. return
  93. }
  94. err = pack.Pack(buf)
  95. if err != nil {
  96. logs.Warn("pack err", err)
  97. common.BuffPool.Put(buf)
  98. return
  99. }
  100. if pack.Flag == common.MUX_NEW_CONN {
  101. logs.Warn("sendinfo mux new conn, insert to write queue", pack.Id)
  102. }
  103. s.writeQueue <- buf
  104. //_, err = buf.WriteTo(s.conn)
  105. //if err != nil {
  106. // s.Close()
  107. // logs.Warn("write err, close mux", err)
  108. //}
  109. //common.BuffPool.Put(buf)
  110. return
  111. }
  112. func (s *Mux) writeSession() {
  113. go func() {
  114. for {
  115. buf := <-s.writeQueue
  116. l := buf.Len()
  117. n, err := buf.WriteTo(s.conn)
  118. common.BuffPool.Put(buf)
  119. if err != nil || int(n) != l {
  120. logs.Warn("close from write session fail ", err, n, l)
  121. s.Close()
  122. break
  123. }
  124. }
  125. }()
  126. <-s.closeChan
  127. }
  128. func (s *Mux) ping() {
  129. go func() {
  130. ticker := time.NewTicker(time.Second * 1)
  131. for {
  132. select {
  133. case <-ticker.C:
  134. }
  135. //Avoid going beyond the scope
  136. if (math.MaxInt32 - s.id) < 10000 {
  137. s.id = 0
  138. }
  139. //logs.Warn("send mux ping")
  140. s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, nil)
  141. if s.pingOk > 10 && s.connType == "kcp" {
  142. s.Close()
  143. break
  144. }
  145. s.pingOk++
  146. }
  147. }()
  148. select {
  149. case <-s.closeChan:
  150. }
  151. }
  152. func (s *Mux) readSession() {
  153. go func() {
  154. pack := common.MuxPack.Get()
  155. for {
  156. pack = common.MuxPack.Get()
  157. if pack.UnPack(s.conn) != nil {
  158. break
  159. }
  160. if pack.Flag != 0 && pack.Flag != 7 {
  161. if pack.Length > 10 {
  162. //logs.Warn(pack.Flag, pack.Id, pack.Length, string(pack.Content[:10]))
  163. }
  164. }
  165. if pack.Flag == common.MUX_NEW_CONN {
  166. logs.Warn("unpack mux new connection", pack.Id)
  167. }
  168. s.pingOk = 0
  169. switch pack.Flag {
  170. case common.MUX_NEW_CONN: //new connection
  171. logs.Warn("rec mux new connection", pack.Id)
  172. conn := NewConn(pack.Id, s)
  173. s.connMap.Set(pack.Id, conn) //it has been set before send ok
  174. s.newConnCh <- conn
  175. go conn.sendWindow.SetAllowSize(512) // set the initial receive window
  176. s.sendInfo(common.MUX_NEW_CONN_OK, pack.Id, nil)
  177. logs.Warn("send mux new connection ok", pack.Id)
  178. continue
  179. case common.MUX_PING_FLAG: //ping
  180. //logs.Warn("send mux ping return")
  181. go s.sendInfo(common.MUX_PING_RETURN, common.MUX_PING, nil)
  182. continue
  183. case common.MUX_PING_RETURN:
  184. continue
  185. }
  186. if connection, ok := s.connMap.Get(pack.Id); ok && !connection.isClose {
  187. switch pack.Flag {
  188. case common.MUX_NEW_MSG: //new msg from remote connection
  189. //insert wait queue
  190. if connection.isClose {
  191. logs.Warn("rec mux new msg closed", pack.Id, string(pack.Content[0:15]))
  192. continue
  193. }
  194. connection.receiveWindow.WriteWg.Add(1)
  195. logs.Warn("rec mux new msg ", pack.Id, string(pack.Content[0:15]))
  196. go func(connection *conn, content []byte) { // do not block read session
  197. _, err := connection.receiveWindow.Write(content)
  198. if err != nil {
  199. logs.Warn("mux new msg err close", err)
  200. s.Close()
  201. }
  202. size := connection.receiveWindow.Size()
  203. if size == 0 {
  204. connection.receiveWindow.WindowFull = true
  205. }
  206. s.sendInfo(common.MUX_MSG_SEND_OK, connection.connId, size)
  207. logs.Warn("send mux new msg ok", pack.Id, size)
  208. connection.receiveWindow.WriteWg.Done()
  209. }(connection, pack.Content)
  210. continue
  211. case common.MUX_NEW_CONN_OK: //connection ok
  212. logs.Warn("rec mux new connection ok ", pack.Id)
  213. connection.connStatusOkCh <- struct{}{}
  214. go connection.sendWindow.SetAllowSize(512)
  215. // set the initial receive window both side
  216. continue
  217. case common.MUX_NEW_CONN_Fail:
  218. logs.Warn("rec mux new connection fail", pack.Id)
  219. connection.connStatusFailCh <- struct{}{}
  220. continue
  221. case common.MUX_MSG_SEND_OK:
  222. if connection.isClose {
  223. logs.Warn("rec mux msg send ok id window closed!", pack.Id, pack.Window)
  224. continue
  225. }
  226. logs.Warn("rec mux msg send ok id window", pack.Id, pack.Window)
  227. go connection.sendWindow.SetAllowSize(pack.Window)
  228. continue
  229. case common.MUX_CONN_CLOSE: //close the connection
  230. logs.Warn("rec mux connection close", pack.Id)
  231. s.connMap.Delete(pack.Id)
  232. connection.closeFlag = true
  233. go func(connection *conn) {
  234. connection.receiveWindow.WriteWg.Wait()
  235. connection.receiveWindow.WriteEndOp <- struct{}{} // close signal to receive window
  236. logs.Warn("receive mux connection close, finish", connection.connId)
  237. }(connection)
  238. continue
  239. }
  240. } else if pack.Flag == common.MUX_CONN_CLOSE {
  241. logs.Warn("rec mux connection close no id ", pack.Id)
  242. continue
  243. }
  244. common.MuxPack.Put(pack)
  245. }
  246. common.MuxPack.Put(pack)
  247. logs.Warn("read session put pack ", pack.Id)
  248. s.Close()
  249. }()
  250. select {
  251. case <-s.closeChan:
  252. }
  253. }
  254. func (s *Mux) Close() error {
  255. logs.Warn("close mux")
  256. if s.IsClose {
  257. return errors.New("the mux has closed")
  258. }
  259. s.IsClose = true
  260. s.connMap.Close()
  261. select {
  262. case s.closeChan <- struct{}{}:
  263. }
  264. select {
  265. case s.closeChan <- struct{}{}:
  266. }
  267. s.closeChan <- struct{}{}
  268. close(s.writeQueue)
  269. close(s.newConnCh)
  270. return s.conn.Close()
  271. }
  272. //get new connId as unique flag
  273. func (s *Mux) getId() (id int32) {
  274. id = atomic.AddInt32(&s.id, 1)
  275. if _, ok := s.connMap.Get(id); ok {
  276. s.getId()
  277. }
  278. return
  279. }