line.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. proxyChannel string // 代理频道
  25. proxyHost *conn.HostInfo // 代理地址
  26. Extra sync.Map // 附加临时信息,由应用端决定具体内容,断线会自动清理
  27. Keep sync.Map // 附加固定信息,由应用端决定具体内容,断线不会自动清理,不过也不能保证一直保持有值,断线后可能会被系统清理
  28. // 当前连接的管道
  29. sendRequest chan *RequestData // 发送请求数据
  30. sendResponse chan *ResponseData // 发送回应包
  31. pingRequest chan *PingData // Ping请求
  32. closeConnect chan bool // 关闭连接信号,true表示外部进行关闭,false表示连接已经出问题或超时关闭
  33. lastRead time.Time // 记录最后一次读到数据的时间,在客户端如果超时则重连
  34. started time.Time // 开始时间
  35. // updated time.Time // 更新时间
  36. }
  37. // 获取当前连接信息
  38. func (c *Line) Host() *conn.HostInfo {
  39. return c.host
  40. }
  41. // 获取开始时间
  42. func (c *Line) Started() time.Time {
  43. return c.started
  44. }
  45. // 获取更新时间
  46. // func (c *Line) Updated() time.Time {
  47. // return c.updated
  48. // }
  49. // 获取当前连接状态
  50. func (c *Line) State() ConnectState {
  51. return c.state
  52. }
  53. // 设置状态
  54. func (c *Line) SetState(state ConnectState) {
  55. if c.state != state {
  56. c.state = state
  57. if c.hub != nil && c.hub.connectStatusFunc != nil {
  58. c.hub.connectStatusFunc(c)
  59. }
  60. }
  61. }
  62. // 获取频道名
  63. func (c *Line) Channel() string {
  64. return c.channel
  65. }
  66. // 设置频道名
  67. // 检查是否包含@,只替换@前面部分
  68. func (c *Line) SetChannelName(name string) {
  69. if strings.Contains(name, "@") {
  70. c.channel = name
  71. } else {
  72. if inx := strings.Index(c.channel, "@"); inx >= 0 {
  73. c.channel = name + c.channel[inx:]
  74. } else {
  75. c.channel = name + "@" + c.channel
  76. }
  77. }
  78. }
  79. // 删除频道名,用于退出登录等操作
  80. func (c *Line) RemoveChannelName() {
  81. if inx := strings.Index(c.channel, "@"); inx >= 0 {
  82. c.channel = c.channel[inx+1:]
  83. }
  84. }
  85. // 频道是否相等,不包括@前面部分和参数部分
  86. func (c *Line) IsChannelEqual(channel string) bool {
  87. if inx := strings.Index(channel, "@"); inx >= 0 {
  88. channel = channel[inx+1:]
  89. }
  90. if inx := strings.Index(channel, "?"); inx > 0 {
  91. channel = channel[0:inx]
  92. }
  93. origin := c.channel
  94. if inx := strings.Index(origin, "@"); inx >= 0 {
  95. origin = origin[inx+1:]
  96. }
  97. if inx := strings.Index(origin, "?"); inx > 0 {
  98. origin = origin[0:inx]
  99. }
  100. return channel == origin
  101. }
  102. // 获取远程的地址
  103. func (c *Line) RemoteIP() net.IP {
  104. defer recover() //避免连接已经关闭而引起panic
  105. return c.conn.RemoteIP()
  106. }
  107. // 获取本地的地址
  108. func (c *Line) LocalIP() net.IP {
  109. defer recover() //避免连接已经关闭而引起panic
  110. return c.conn.LocalIP()
  111. }
  112. // 获取通讯消息ID号
  113. func (c *Line) getPingID() uint16 {
  114. c.pingID++
  115. if c.pingID <= 0 || c.pingID >= config.ID_MAX {
  116. c.pingID = 1
  117. }
  118. return c.pingID
  119. }
  120. // 读信息循环通道,采用新线程
  121. func (c *Line) readPump() {
  122. for {
  123. if c.state == StateProxied && c.proxyConn != nil {
  124. buf, recycle, err := c.conn.ReadRawPackage(c.cf.LongReadWait)
  125. if err != nil {
  126. if !strings.Contains(err.Error(), "EOF") {
  127. log.Println("[readPump] ReadRawPackage:", err)
  128. }
  129. c.Close(false)
  130. return
  131. }
  132. c.lastRead = time.Now()
  133. // 转发消息到代理端
  134. err = c.proxyConn.WriteRawPackage(buf, recycle)
  135. if err != nil {
  136. log.Println("[readPump] WriteRawPackage:", err)
  137. return
  138. }
  139. } else if c.state == StateClosed || c.state == StateDisconnected {
  140. return
  141. } else {
  142. msgType, id, cmd, state, data, err := c.conn.ReadMessage(c.cf.LongReadWait)
  143. if err != nil {
  144. c.Close(false)
  145. if !strings.Contains(err.Error(), "EOF") {
  146. log.Println("[readPump]", err)
  147. }
  148. return
  149. }
  150. // 记录最后读到数据的时间
  151. c.lastRead = time.Now()
  152. switch msgType {
  153. case conn.MsgPing:
  154. // ping或pong包
  155. c.pingRequest <- &PingData{
  156. Id: id,
  157. }
  158. case conn.MsgRequest:
  159. // 请求数据包
  160. go c.hub.requestFromNet(&RequestData{
  161. Id: id,
  162. Cmd: cmd,
  163. Data: data,
  164. conn: c,
  165. })
  166. case conn.MsgResponse:
  167. // 网络回应数据包
  168. go c.hub.outResponse(&ResponseData{
  169. Id: id,
  170. State: state & 0x7F,
  171. Data: data,
  172. conn: c,
  173. })
  174. case conn.MsgProxyConnect:
  175. c.SetState(StateProxing)
  176. // 建立代理连接
  177. host, err := conn.ParseUrl(string(data))
  178. if err != nil {
  179. log.Println("[MsgProxyConnect] ParseUrl:", err)
  180. c.Close(false)
  181. return
  182. }
  183. proxyConn, err := DailWithTimeout(c.hub.ctx, host, c.cf)
  184. if err != nil {
  185. log.Println("[MsgProxyConnect] DailWithTimeout:", err)
  186. // 发送失败状态包
  187. c.conn.WriteRawPackage(conn.ProxyResultPackageEncode(err.Error()), true)
  188. c.Close(false)
  189. return
  190. }
  191. c.proxyConn = proxyConn
  192. c.proxyHost = host
  193. c.SetState(StateProxied)
  194. // not news is good news
  195. c.conn.WriteRawPackage(conn.ProxyResultPackageEncode(""), true)
  196. go c.proxyDump()
  197. default:
  198. log.Println("[readPump] unknown msg error:", msgType, id, cmd, state, string(data))
  199. }
  200. }
  201. }
  202. }
  203. // 代理情况下的消息转发
  204. // 会一直阻塞
  205. func (c *Line) proxyDump() {
  206. defer c.proxyConn.Close()
  207. for {
  208. if c.state == StateProxied && c.proxyConn != nil {
  209. buf, recycle, err := c.proxyConn.ReadRawPackage(c.cf.LongReadWait)
  210. if err != nil {
  211. c.Close(false)
  212. return
  213. }
  214. // 转发消息到代理端
  215. err = c.conn.WriteRawPackage(buf, recycle)
  216. if err != nil {
  217. log.Println("[proxyDump] WriteRawPackage:", err)
  218. return
  219. }
  220. } else if c.state == StateClosed || c.state == StateDisconnected {
  221. return
  222. } else {
  223. time.Sleep(time.Second)
  224. }
  225. }
  226. }
  227. // 检查管道并处理不同的消息,新go程调用
  228. // 为了防止多线程的冲突,主要的处理都在这里进行
  229. func (c *Line) writePump() {
  230. pingTicker := time.NewTicker(time.Duration(c.cf.PingInterval * int(time.Millisecond)))
  231. // 定义恢复函数
  232. defer func() {
  233. pingTicker.Stop()
  234. c.conn.Close()
  235. // 检查是否需要重新连接
  236. if c.autoReconnect && c.host != nil && c.state != StateClosed && c.state != StateConnected {
  237. go func() {
  238. defer func() {
  239. if err := recover(); err != nil {
  240. c.SetState(StateDisconnected)
  241. log.Println(err)
  242. debug.PrintStack()
  243. }
  244. }()
  245. c.host.Errors++
  246. c.host.Updated = time.Now()
  247. delay := 5 * time.Second * time.Duration(c.host.Errors)
  248. log.Println("[Line] will reconnect with delay:", delay)
  249. time.Sleep(delay)
  250. if c.host.Errors < 2 {
  251. c.hub.ConnectToServerX(c.channel, false, c.host)
  252. } else {
  253. c.hub.ConnectToServerX(c.channel, false, nil)
  254. }
  255. }()
  256. }
  257. }()
  258. // 清空closeConnect
  259. c.cleanClose()
  260. // 开始处理信息循环
  261. for {
  262. select {
  263. case request := <-c.sendRequest: // 发送请求包
  264. err := c.conn.WriteRequest(request.Id, request.Cmd, request.Data)
  265. if err != nil {
  266. log.Println("[writePump WriteRequest]", err)
  267. return
  268. }
  269. case response := <-c.sendResponse: // 接收到的响应包
  270. // 发送响应数据
  271. err := c.conn.WriteResponse(response.Id, response.State, response.Data)
  272. if err != nil {
  273. log.Println("[writePump WriteResponse]", err)
  274. return
  275. }
  276. case ping := <-c.pingRequest: // 发送ping包到网络
  277. if c.cf.PrintPing {
  278. log.Println("[PING]<-", c.channel, ping.Id)
  279. }
  280. // 只有服务器端需要回应ping包
  281. if c.host == nil {
  282. if c.cf.PrintPing {
  283. log.Println("[RESP PING]->", c.channel, ping.Id)
  284. }
  285. err := c.conn.WritePing(ping.Id)
  286. if err != nil {
  287. log.Println("[ping] failed", err)
  288. return
  289. }
  290. } else {
  291. // 检查 ping id 是否正确
  292. if c.pingID == ping.Id {
  293. c.pingWrongCount = 0
  294. } else {
  295. c.pingWrongCount++
  296. if c.pingWrongCount > 3 {
  297. log.Println("[wrong ping id]", ping.Id)
  298. c.Close(false)
  299. return
  300. }
  301. }
  302. }
  303. case <-pingTicker.C:
  304. // 检查是否已经很久时间没有使用连接了
  305. dr := time.Since(c.lastRead).Milliseconds()
  306. if dr > int64(c.cf.PingInterval)*5 {
  307. // 超时关闭当前的连接
  308. if c.cf.PrintMsg {
  309. log.Println("[Connect timeout]", c.channel)
  310. }
  311. // 有可能连接出现问题,断开并重新连接
  312. // if c.host != nil || c.proxyHost != nil {
  313. c.Close(false)
  314. return
  315. // }
  316. }
  317. // 只需要客户端发送
  318. if c.host != nil {
  319. // 发送ping包
  320. if dr >= int64(c.cf.PingInterval) {
  321. id := c.getPingID()
  322. // 发送ping数据包
  323. if c.cf.PrintPing {
  324. log.Println("[SEND PING]->", c.channel, id)
  325. }
  326. err := c.conn.WritePing(id)
  327. if err != nil {
  328. log.Println("[writePump WritePing]", err)
  329. return
  330. }
  331. }
  332. }
  333. case <-c.closeConnect:
  334. c.cleanClose()
  335. // 退出循环
  336. return
  337. }
  338. }
  339. }
  340. // 关闭连接
  341. func (c *Line) Close(quick bool) {
  342. defer recover() //避免管道已经关闭而引起panic
  343. c.conn.Close()
  344. if c.proxyConn != nil {
  345. c.proxyConn.Close()
  346. c.proxyConn = nil
  347. }
  348. c.proxyChannel = ""
  349. c.proxyHost = nil
  350. c.closeConnect <- quick
  351. if quick {
  352. c.SetState(StateClosed)
  353. c.hub.removeLine(c)
  354. } else if c.state != StateClosed {
  355. c.SetState(StateDisconnected)
  356. go c.hub.cleanDeadConnect()
  357. }
  358. c.Extra.Clear()
  359. // c.updated = time.Now()
  360. }
  361. // 清空余留下来的管道消息
  362. func (c *Line) cleanClose() {
  363. for {
  364. select {
  365. case <-c.closeConnect:
  366. default:
  367. return
  368. }
  369. }
  370. }
  371. // 连接开始运行
  372. func (c *Line) Start(channel string, conn conn.Connect, host *conn.HostInfo) {
  373. now := time.Now()
  374. // c.updated = now
  375. c.lastRead = now // 避免默认为0时被清理
  376. c.channel = channel
  377. c.conn = conn
  378. c.host = host
  379. if c.host != nil && c.proxyChannel != "" {
  380. // 进行代理连接
  381. c.SetState(StateProxing)
  382. err := c.hub.ClientProxyConnect(c, c.channel+"<-"+c.proxyChannel)
  383. if err != nil {
  384. log.Println("[ProxyConnect] error:", err)
  385. c.Close(false)
  386. } else {
  387. c.SetState(StateProxied)
  388. }
  389. go c.readPump()
  390. go c.writePump()
  391. } else {
  392. c.SetState(StateConnected)
  393. go c.readPump()
  394. go c.writePump()
  395. }
  396. }
  397. // 请求入口函数
  398. func NewConnect(
  399. cf *config.Config,
  400. hub *Hub,
  401. channel string,
  402. proxyChannel string,
  403. conn conn.Connect,
  404. host *conn.HostInfo,
  405. autoReconnect bool,
  406. ) *Line {
  407. now := time.Now()
  408. cc := &Line{
  409. cf: cf,
  410. channel: channel,
  411. hub: hub,
  412. pingID: uint16(now.UnixNano()) % config.ID_MAX,
  413. autoReconnect: autoReconnect,
  414. proxyChannel: proxyChannel,
  415. sendRequest: make(chan *RequestData, 32),
  416. sendResponse: make(chan *ResponseData, 32),
  417. pingRequest: make(chan *PingData, 5),
  418. closeConnect: make(chan bool, 5),
  419. lastRead: now, // 避免默认为0时被清理
  420. started: now,
  421. // updated: now,
  422. }
  423. cc.Start(channel, conn, host)
  424. return cc
  425. }