line.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. defer recover() //避免连接已经关闭而引起panic
  95. return c.conn.RemoteIP()
  96. }
  97. // 获取本地的地址
  98. func (c *Line) LocalIP() net.IP {
  99. defer recover() //避免连接已经关闭而引起panic
  100. return c.conn.LocalIP()
  101. }
  102. // 获取通讯消息ID号
  103. func (c *Line) getPingID() uint16 {
  104. c.pingID++
  105. if c.pingID <= 0 || c.pingID >= config.ID_MAX {
  106. c.pingID = 1
  107. }
  108. return c.pingID
  109. }
  110. // 读信息循环通道,采用新线程
  111. func (c *Line) readPump() {
  112. for {
  113. switch c.state {
  114. case StateConnected: // 已经连接好啦,正常通信状态
  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]", err)
  119. }
  120. c.Close(false)
  121. return
  122. }
  123. // 记录最后读到数据的时间
  124. c.lastRead = time.Now()
  125. switch msgType {
  126. case conn.MsgPing:
  127. // ping或pong包
  128. c.pingRequest <- &PingData{
  129. Id: id,
  130. }
  131. case conn.MsgRequest:
  132. // 请求数据包
  133. go c.hub.requestFromNet(&RequestData{
  134. Id: id,
  135. Cmd: cmd,
  136. Data: data,
  137. conn: c,
  138. })
  139. case conn.MsgResponse:
  140. // 网络回应数据包
  141. go c.hub.outResponse(&ResponseData{
  142. Id: id,
  143. State: state & 0x7F,
  144. Data: data,
  145. conn: c,
  146. })
  147. case conn.MsgProxyConnect:
  148. // TODO: 建立代理连接
  149. }
  150. case StateProxied: // 已经处于代理状态
  151. buf, recycle, err := c.conn.ReadRawPackage(c.cf.LongReadWait)
  152. if err != nil {
  153. if !strings.Contains(err.Error(), "EOF") {
  154. log.Println("[StateProxied] ReadRawPackage:", err)
  155. }
  156. c.Close(false)
  157. return
  158. }
  159. // 转发消息到代理端
  160. err = c.proxyConn.WriteRawPackage(buf, recycle)
  161. if err != nil {
  162. log.Println("[StateProxied] WriteRawPackage:", err)
  163. return
  164. }
  165. case StateClosed:
  166. return
  167. default:
  168. time.Sleep(time.Second)
  169. }
  170. }
  171. }
  172. // 检查管道并处理不同的消息,新go程调用
  173. // 为了防止多线程的冲突,主要的处理都在这里进行
  174. func (c *Line) writePump() {
  175. pingTicker := time.NewTicker(time.Duration(c.cf.PingInterval * int(time.Millisecond)))
  176. // 定义恢复函数
  177. defer func() {
  178. pingTicker.Stop()
  179. c.conn.Close()
  180. // 检查是否需要重新连接
  181. if c.autoReconnect && c.host != nil && c.state != StateClosed && c.state != StateConnected {
  182. go func() {
  183. defer func() {
  184. if err := recover(); err != nil {
  185. c.state = StateDisconnected
  186. log.Println(err)
  187. debug.PrintStack()
  188. }
  189. }()
  190. c.host.Errors++
  191. c.host.Updated = time.Now()
  192. delay := 5 * time.Second * time.Duration(c.host.Errors)
  193. log.Println("[Line] will reconnect with delay:", delay)
  194. time.Sleep(delay)
  195. if c.host.Errors < 2 {
  196. c.hub.ConnectToServerX(c.channel, false, c.host)
  197. } else {
  198. c.hub.ConnectToServerX(c.channel, false, nil)
  199. }
  200. }()
  201. }
  202. }()
  203. // 清空closeConnect
  204. c.cleanClose()
  205. // 开始处理信息循环
  206. for {
  207. select {
  208. case request := <-c.sendRequest: // 发送请求包
  209. err := c.conn.WriteRequest(request.Id, request.Cmd, request.Data)
  210. if err != nil {
  211. log.Println("[writePump WriteRequest]", err)
  212. return
  213. }
  214. case response := <-c.sendResponse: // 接收到的响应包
  215. // 发送响应数据
  216. err := c.conn.WriteResponse(response.Id, response.State, response.Data)
  217. if err != nil {
  218. log.Println("[writePump WriteResponse]", err)
  219. return
  220. }
  221. case ping := <-c.pingRequest: // 发送ping包到网络
  222. if c.cf.PrintPing {
  223. log.Println("[PING]<-", c.channel, ping.Id)
  224. }
  225. // 只有服务器端需要回应ping包
  226. if c.host == nil {
  227. if c.cf.PrintPing {
  228. log.Println("[RESP PING]->", c.channel, ping.Id)
  229. }
  230. err := c.conn.WritePing(ping.Id)
  231. if err != nil {
  232. log.Println("[ping] failed", err)
  233. return
  234. }
  235. } else {
  236. // 检查 ping id 是否正确
  237. if c.pingID == ping.Id {
  238. c.pingWrongCount = 0
  239. } else {
  240. c.pingWrongCount++
  241. if c.pingWrongCount > 3 {
  242. log.Println("[wrong ping id]", ping.Id)
  243. c.Close(false)
  244. return
  245. }
  246. }
  247. }
  248. case <-pingTicker.C:
  249. // 检查是否已经很久时间没有使用连接了
  250. dr := time.Since(c.lastRead)
  251. if dr > time.Duration(c.cf.PingInterval*3*int(time.Millisecond)) {
  252. // 超时关闭当前的连接
  253. log.Println("[Connect timeout]", c.channel)
  254. // 有可能连接出现问题,断开并重新连接
  255. // 检测到浏览器会出现休眠的状态,服务端就不主动关闭,只有客户端关闭
  256. if c.host != nil {
  257. c.Close(false)
  258. return
  259. }
  260. }
  261. // 只需要客户端发送
  262. if c.host != nil {
  263. // 发送ping包
  264. if dr >= time.Duration(c.cf.PingInterval*int(time.Millisecond)) {
  265. id := c.getPingID()
  266. // 发送ping数据包
  267. if c.cf.PrintPing {
  268. log.Println("[SEND PING]->", c.channel, id)
  269. }
  270. err := c.conn.WritePing(id)
  271. if err != nil {
  272. log.Println("[writePump WritePing]", err)
  273. return
  274. }
  275. }
  276. }
  277. case <-c.closeConnect:
  278. c.cleanClose()
  279. // 退出循环
  280. return
  281. }
  282. }
  283. }
  284. // 关闭连接
  285. func (c *Line) Close(quick bool) {
  286. defer recover() //避免管道已经关闭而引起panic
  287. c.conn.Close()
  288. c.closeConnect <- quick
  289. if quick {
  290. if c.state != StateClosed {
  291. c.state = StateClosed
  292. c.hub.connectStatusFunc(c)
  293. }
  294. c.hub.removeLine(c)
  295. } else {
  296. if c.state != StateDisconnected {
  297. c.state = StateDisconnected
  298. c.hub.connectStatusFunc(c)
  299. go c.hub.cleanDeadConnect()
  300. }
  301. }
  302. c.Extra.Clear()
  303. // c.updated = time.Now()
  304. }
  305. // 清空余留下来的管道消息
  306. func (c *Line) cleanClose() {
  307. for {
  308. select {
  309. case <-c.closeConnect:
  310. default:
  311. return
  312. }
  313. }
  314. }
  315. // 连接开始运行
  316. func (c *Line) Start(channel string, conn conn.Connect, host *conn.HostInfo) {
  317. now := time.Now()
  318. c.updated = now
  319. c.lastRead = now // 避免默认为0时被清理
  320. c.channel = channel
  321. c.conn = conn
  322. c.host = host
  323. c.state = StateConnected
  324. go c.readPump()
  325. go c.writePump()
  326. c.hub.connectStatusFunc(c)
  327. }
  328. // 请求入口函数
  329. func NewConnect(
  330. cf *config.Config,
  331. hub *Hub,
  332. channel string,
  333. conn conn.Connect,
  334. host *conn.HostInfo,
  335. autoReconnect bool,
  336. ) *Line {
  337. now := time.Now()
  338. cc := &Line{
  339. cf: cf,
  340. channel: channel,
  341. hub: hub,
  342. pingID: uint16(now.UnixNano()) % config.ID_MAX,
  343. autoReconnect: autoReconnect,
  344. sendRequest: make(chan *RequestData, 32),
  345. sendResponse: make(chan *ResponseData, 32),
  346. pingRequest: make(chan *PingData, 5),
  347. closeConnect: make(chan bool, 5),
  348. lastRead: now, // 避免默认为0时被清理
  349. started: now,
  350. updated: now,
  351. }
  352. cc.Start(channel, conn, host)
  353. return cc
  354. }