line.go 8.3 KB

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