line.go 6.7 KB

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