line.go 8.7 KB

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