line.go 8.1 KB

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