line.go 8.6 KB

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