line.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. time.Sleep(5 * time.Second * time.Duration(c.host.Errors))
  165. if c.host.Errors < 2 {
  166. c.hub.ConnectToServerX(c.channel, false, c.host)
  167. } else {
  168. c.hub.ConnectToServerX(c.channel, false, nil)
  169. }
  170. }()
  171. }
  172. }()
  173. // 清空closeConnect
  174. c.cleanClose()
  175. // 开始处理信息循环
  176. for {
  177. select {
  178. case request := <-c.sendRequest: // 发送请求包
  179. err := c.conn.WriteRequest(request.Id, request.Cmd, request.Data)
  180. if err != nil {
  181. log.Println("[writePump WriteRequest]", err)
  182. return
  183. }
  184. case response := <-c.sendResponse: // 接收到的响应包
  185. // 发送响应数据
  186. err := c.conn.WriteResponse(response.Id, response.State, response.Data)
  187. if err != nil {
  188. log.Println("[writePump WriteResponse]", err)
  189. return
  190. }
  191. case ping := <-c.pingRequest: // 发送ping包到网络
  192. if c.cf.PrintPing {
  193. log.Println("[PING]<-", c.channel, ping.Id)
  194. }
  195. // 只有服务器端需要回应ping包
  196. if c.host == nil {
  197. if c.cf.PrintPing {
  198. log.Println("[RESP PING]->", c.channel, ping.Id)
  199. }
  200. err := c.conn.WritePing(ping.Id)
  201. if err != nil {
  202. log.Println("[ping ERROR]", err)
  203. return
  204. }
  205. } else {
  206. // 检查 ping id 是否正确
  207. if c.pingID == ping.Id {
  208. c.pingWrongCount = 0
  209. } else {
  210. c.pingWrongCount++
  211. if c.pingWrongCount > 3 {
  212. log.Println("[wrong ping id]", ping.Id)
  213. c.Close(false)
  214. return
  215. }
  216. }
  217. }
  218. case <-pingTicker.C:
  219. // 检查是否已经很久时间没有使用连接了
  220. dr := time.Since(c.lastRead)
  221. if dr > time.Duration(c.cf.PingInterval*3*int(time.Millisecond)) {
  222. // 超时关闭当前的连接
  223. log.Println("[Connect timeout and stop it]", c.channel)
  224. // 有可能连接出现问题,断开并重新连接
  225. c.Close(false)
  226. return
  227. }
  228. // 只需要客户端发送
  229. if c.host != nil {
  230. // 发送ping包
  231. if dr >= time.Duration(c.cf.PingInterval*int(time.Millisecond)) {
  232. id := c.getPingID()
  233. // 发送ping数据包
  234. if c.cf.PrintPing {
  235. log.Println("[SEND PING]->", c.channel, id)
  236. }
  237. err := c.conn.WritePing(id)
  238. if err != nil {
  239. log.Println("[writePump WritePing]", err)
  240. return
  241. }
  242. }
  243. }
  244. case <-c.closeConnect:
  245. c.cleanClose()
  246. // 退出循环
  247. return
  248. }
  249. }
  250. }
  251. // 关闭连接
  252. func (c *Line) Close(quick bool) {
  253. defer recover() //避免管道已经关闭而引起panic
  254. c.conn.Close()
  255. c.closeConnect <- quick
  256. if quick {
  257. if c.state != Closed {
  258. c.state = Closed
  259. c.hub.connectStatusFunc(c)
  260. }
  261. c.hub.removeLine(c)
  262. } else {
  263. if c.state != Disconnected {
  264. c.state = Disconnected
  265. c.hub.connectStatusFunc(c)
  266. go c.hub.cleanDeadConnect()
  267. }
  268. }
  269. c.Extra.Clear()
  270. c.updated = time.Now()
  271. }
  272. // 清空余留下来的管道消息
  273. func (c *Line) cleanClose() {
  274. for {
  275. select {
  276. case <-c.closeConnect:
  277. default:
  278. return
  279. }
  280. }
  281. }
  282. // 连接开始运行
  283. func (c *Line) Start(channel string, conn conn.Connect, host *HostInfo) {
  284. now := time.Now()
  285. c.updated = now
  286. c.lastRead = now // 避免默认为0时被清理
  287. c.channel = channel
  288. c.conn = conn
  289. c.host = host
  290. go c.readPump()
  291. go c.writePump()
  292. c.state = Connected
  293. c.hub.connectStatusFunc(c)
  294. }
  295. // 请求入口函数
  296. func NewConnect(
  297. cf *config.Config,
  298. hub *Hub,
  299. channel string,
  300. conn conn.Connect,
  301. host *HostInfo,
  302. autoReconnect bool,
  303. ) *Line {
  304. now := time.Now()
  305. cc := &Line{
  306. cf: cf,
  307. channel: channel,
  308. hub: hub,
  309. pingID: uint16(now.UnixNano()) % config.ID_MAX,
  310. autoReconnect: autoReconnect,
  311. sendRequest: make(chan *RequestData, 32),
  312. sendResponse: make(chan *ResponseData, 32),
  313. pingRequest: make(chan *PingData, 5),
  314. closeConnect: make(chan bool, 5),
  315. lastRead: now, // 避免默认为0时被清理
  316. started: now,
  317. updated: now,
  318. }
  319. cc.Start(channel, conn, host)
  320. return cc
  321. }