line.go 7.8 KB

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