line.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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) * 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(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(err)
  162. return
  163. }
  164. case ping := <-c.pingRequest: // 发送ping包到网络
  165. // 只有服务器端需要回应ping包
  166. if c.host == nil {
  167. err := c.conn.WritePing(ping.Id)
  168. if err != nil {
  169. log.Println("[ping ERROR]", err)
  170. return
  171. }
  172. } else {
  173. // 检查 ping id 是否正确
  174. if c.pingID == ping.Id {
  175. c.pingWrongCount = 0
  176. } else {
  177. c.pingWrongCount++
  178. if c.pingWrongCount > 3 {
  179. log.Println("[wrong ping id]", ping.Id)
  180. c.Close(false)
  181. return
  182. }
  183. }
  184. }
  185. case <-pingTicker.C:
  186. // 检查是否已经很久时间没有使用连接了
  187. dr := time.Since(c.lastRead)
  188. if dr > time.Duration(c.cf.PingInterval*3)*time.Millisecond {
  189. // 超时关闭当前的连接
  190. log.Println("Connect timeout and stop it", c.channel)
  191. // 有可能连接出现问题,断开并重新连接
  192. c.Close(false)
  193. return
  194. }
  195. // 只需要客户端发送
  196. if c.host != nil {
  197. // 发送ping包
  198. if dr > time.Duration(c.cf.PingInterval) {
  199. // 发送ping数据包
  200. err := c.conn.WritePing(c.getPingID())
  201. if err != nil {
  202. log.Println(err)
  203. return
  204. }
  205. }
  206. }
  207. case <-c.closeConnect:
  208. c.cleanClose()
  209. // 退出循环
  210. return
  211. }
  212. }
  213. }
  214. // 关闭连接
  215. func (c *Line) Close(quick bool) {
  216. defer recover() //避免管道已经关闭而引起panic
  217. c.conn.Close()
  218. c.closeConnect <- quick
  219. c.updated = time.Now()
  220. if quick {
  221. if c.state != Closed {
  222. c.state = Closed
  223. c.hub.connectStatusFunc(c)
  224. }
  225. c.hub.removeLine(c)
  226. } else {
  227. if c.state != Disconnected {
  228. c.state = Disconnected
  229. c.hub.connectStatusFunc(c)
  230. go c.hub.cleanDeadConnect()
  231. }
  232. }
  233. }
  234. // 清空余留下来的管道消息
  235. func (c *Line) cleanClose() {
  236. for {
  237. select {
  238. case <-c.closeConnect:
  239. default:
  240. return
  241. }
  242. }
  243. }
  244. // 连接开始运行
  245. func (c *Line) Start(conn conn.Connect, host *HostInfo) {
  246. c.updated = time.Now()
  247. c.conn = conn
  248. c.host = host
  249. go c.readPump()
  250. go c.writePump()
  251. c.state = Connected
  252. c.hub.connectStatusFunc(c)
  253. }
  254. // 请求入口函数
  255. func NewConnect(
  256. cf *config.Config,
  257. hub *Hub,
  258. channel string,
  259. conn conn.Connect,
  260. host *HostInfo,
  261. ) *Line {
  262. cc := &Line{
  263. cf: cf,
  264. channel: channel,
  265. hub: hub,
  266. sendRequest: make(chan *RequestData, 32),
  267. sendResponse: make(chan *ResponseData, 32),
  268. pingRequest: make(chan *PingData, 5),
  269. closeConnect: make(chan bool, 5),
  270. lastRead: time.Now(), // 避免默认为0时被清理
  271. started: time.Now(),
  272. }
  273. cc.Start(conn, host)
  274. return cc
  275. }