line.go 6.6 KB

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