line.go 7.8 KB

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