line.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package tinymq
  2. import (
  3. "log"
  4. "net"
  5. "strings"
  6. "time"
  7. "git.me9.top/git/tinymq/config"
  8. "git.me9.top/git/tinymq/conn"
  9. )
  10. // 建立一个虚拟连接,包括生成命令,发送命令和响应命令
  11. type Line struct {
  12. cf *config.Config
  13. hub *Hub
  14. conn conn.Connect
  15. channel string // 连接对端的频道
  16. state ConnectState
  17. host *HostInfo // 如果有值说明是客户端,就是主动连接端
  18. pingID uint16 // 只有客户端使用
  19. pingWrongCount uint8 // 记录 ping id 反馈错误次数,超过3次则重新连接
  20. // 当前连接的管道
  21. sendRequest chan *RequestData // 发送请求数据
  22. sendResponse chan *ResponseData // 发送回应包
  23. pingRequest chan *PingData // Ping请求
  24. closeConnect chan bool // 关闭连接信号,true表示外部进行关闭,false表示连接已经出问题或超时关闭
  25. lastRead time.Time // 记录最后一次读到数据的时间,在客户端如果超时则重连
  26. started time.Time // 开始时间
  27. updated time.Time // 更新时间
  28. }
  29. // 获取开始时间
  30. func (c *Line) Started() time.Time {
  31. return c.started
  32. }
  33. // 获取更新时间
  34. func (c *Line) Updated() time.Time {
  35. return c.updated
  36. }
  37. // 获取当前连接状态
  38. func (c *Line) State() ConnectState {
  39. return c.state
  40. }
  41. // 获取频道名
  42. func (c *Line) Channel() string {
  43. return c.channel
  44. }
  45. // 获取远程的地址
  46. func (c *Line) RemoteAddr() net.Addr {
  47. if c.state == Connected {
  48. return c.conn.RemoteAddr()
  49. } else {
  50. return nil
  51. }
  52. }
  53. // 获取本地的地址
  54. func (c *Line) LocalAddr() net.Addr {
  55. if c.state == Connected {
  56. return c.conn.LocalAddr()
  57. } else {
  58. return nil
  59. }
  60. }
  61. // 获取通讯消息ID号
  62. func (c *Line) getPingID() uint16 {
  63. c.pingID++
  64. if c.pingID <= 0 || c.pingID >= config.ID_MAX {
  65. c.pingID = 1
  66. }
  67. return c.pingID
  68. }
  69. // 设置频道名
  70. func (c *Line) SetChannelName(name string) {
  71. if strings.Contains(name, "@") {
  72. c.channel = name
  73. } else {
  74. if inx := strings.Index(c.channel, "@"); inx >= 0 {
  75. c.channel = name + c.channel[inx:]
  76. } else {
  77. c.channel = name + "@" + c.channel
  78. }
  79. }
  80. }
  81. // 读信息循环通道,采用新线程
  82. func (c *Line) readPump() {
  83. for {
  84. msgType, id, cmd, state, data, err := c.conn.ReadMessage(c.cf.LongReadWait)
  85. if err != nil {
  86. if !strings.Contains(err.Error(), "EOF") {
  87. log.Println("[readPump ERROR]", err)
  88. }
  89. c.Close(false)
  90. return
  91. }
  92. // 记录最后读到数据的时间
  93. c.lastRead = time.Now()
  94. switch msgType {
  95. case conn.PingMsg:
  96. // ping或pong包
  97. c.pingRequest <- &PingData{
  98. Id: id,
  99. }
  100. case conn.RequestMsg:
  101. // 请求数据包
  102. go c.hub.requestFromNet(&RequestData{
  103. Id: id,
  104. Cmd: cmd,
  105. Data: data,
  106. conn: c,
  107. })
  108. case conn.ResponseMsg:
  109. // 网络回应数据包
  110. go c.hub.outResponse(&ResponseData{
  111. Id: id,
  112. State: state & 0x7F,
  113. Data: data,
  114. conn: c,
  115. })
  116. }
  117. }
  118. }
  119. // 检查管道并处理不同的消息,新go程调用
  120. // 为了防止多线程的冲突,主要的处理都在这里进行
  121. func (c *Line) writePump() {
  122. pingTicker := time.NewTicker(time.Duration(c.cf.PingInterval) * time.Millisecond)
  123. // 定义恢复函数
  124. defer func() {
  125. pingTicker.Stop()
  126. c.conn.Close()
  127. // 检查是否需要重新连接
  128. if c.host != nil && c.state != Closed && c.state != Connected {
  129. go func() {
  130. c.host.Errors++
  131. c.host.Updated = time.Now()
  132. time.Sleep(time.Second)
  133. c.hub.ConnectToServerX(c.channel, false)
  134. }()
  135. }
  136. }()
  137. // 清空closeConnect
  138. c.cleanClose()
  139. // 开始处理信息循环
  140. for {
  141. select {
  142. case request := <-c.sendRequest: // 发送请求包
  143. err := c.conn.WriteRequest(request.Id, request.Cmd, request.Data)
  144. if err != nil {
  145. log.Println(err)
  146. return
  147. }
  148. case response := <-c.sendResponse: // 接收到的响应包
  149. // 发送响应数据
  150. err := c.conn.WriteResponse(response.Id, response.State, response.Data)
  151. if err != nil {
  152. log.Println(err)
  153. return
  154. }
  155. case ping := <-c.pingRequest: // 发送ping包到网络
  156. // 只有服务器端需要回应ping包
  157. if c.host == nil {
  158. err := c.conn.WritePing(ping.Id)
  159. if err != nil {
  160. log.Println("[ping ERROR]", err)
  161. return
  162. }
  163. } else {
  164. // 检查 ping id 是否正确
  165. if c.pingID == ping.Id {
  166. c.pingWrongCount = 0
  167. } else {
  168. c.pingWrongCount++
  169. if c.pingWrongCount > 3 {
  170. log.Println("[wrong ping id]", ping.Id)
  171. c.Close(false)
  172. return
  173. }
  174. }
  175. }
  176. case <-pingTicker.C:
  177. // 检查是否已经很久时间没有使用连接了
  178. dr := time.Since(c.lastRead)
  179. if dr > time.Duration(c.cf.PingInterval*3)*time.Millisecond {
  180. // 超时关闭当前的连接
  181. log.Println("Connect timeout and stop it", c.channel)
  182. // 有可能连接出现问题,断开并重新连接
  183. c.Close(false)
  184. return
  185. }
  186. // 只需要客户端发送
  187. if c.host != nil {
  188. // 发送ping包
  189. if dr > time.Duration(c.cf.PingInterval) {
  190. // 发送ping数据包
  191. err := c.conn.WritePing(c.getPingID())
  192. if err != nil {
  193. log.Println(err)
  194. return
  195. }
  196. }
  197. }
  198. case <-c.closeConnect:
  199. c.cleanClose()
  200. // 退出循环
  201. return
  202. }
  203. }
  204. }
  205. // 关闭连接
  206. func (c *Line) Close(quick bool) {
  207. defer recover() //避免管道已经关闭而引起panic
  208. c.conn.Close()
  209. c.closeConnect <- quick
  210. c.updated = time.Now()
  211. if quick {
  212. if c.state != Closed {
  213. c.state = Closed
  214. c.hub.connectStatusFunc(c)
  215. }
  216. c.hub.removeLine(c)
  217. } else {
  218. if c.state != Disconnected {
  219. c.state = Disconnected
  220. c.hub.connectStatusFunc(c)
  221. go c.hub.cleanDeadConnect()
  222. }
  223. }
  224. }
  225. // 清空余留下来的管道消息
  226. func (c *Line) cleanClose() {
  227. for {
  228. select {
  229. case <-c.closeConnect:
  230. default:
  231. return
  232. }
  233. }
  234. }
  235. // 连接开始运行
  236. func (c *Line) Start(conn conn.Connect, host *HostInfo) {
  237. c.updated = time.Now()
  238. c.conn = conn
  239. c.host = host
  240. go c.readPump()
  241. go c.writePump()
  242. c.state = Connected
  243. c.hub.connectStatusFunc(c)
  244. }
  245. // 请求入口函数
  246. func NewConnect(
  247. cf *config.Config,
  248. hub *Hub,
  249. channel string,
  250. conn conn.Connect,
  251. host *HostInfo,
  252. ) *Line {
  253. cc := &Line{
  254. cf: cf,
  255. channel: channel,
  256. hub: hub,
  257. sendRequest: make(chan *RequestData, 32),
  258. sendResponse: make(chan *ResponseData, 32),
  259. pingRequest: make(chan *PingData, 5),
  260. closeConnect: make(chan bool, 5),
  261. lastRead: time.Now(), // 避免默认为0时被清理
  262. started: time.Now(),
  263. }
  264. cc.Start(conn, host)
  265. return cc
  266. }