line.go 7.1 KB

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