line.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. if !strings.Contains(err.Error(), "EOF") {
  145. log.Println("[readPump]", err)
  146. }
  147. return
  148. }
  149. // 记录最后读到数据的时间
  150. c.lastRead = time.Now()
  151. switch msgType {
  152. case conn.MsgPing:
  153. // ping或pong包
  154. c.pingRequest <- &PingData{
  155. Id: id,
  156. }
  157. case conn.MsgRequest:
  158. // 请求数据包
  159. go c.hub.requestFromNet(&RequestData{
  160. Id: id,
  161. Cmd: cmd,
  162. Data: data,
  163. conn: c,
  164. })
  165. case conn.MsgResponse:
  166. // 网络回应数据包
  167. go c.hub.outResponse(&ResponseData{
  168. Id: id,
  169. State: state & 0x7F,
  170. Data: data,
  171. conn: c,
  172. })
  173. case conn.MsgProxyConnect:
  174. c.SetState(StateProxing)
  175. // 建立代理连接
  176. host, err := conn.ParseUrl(string(data))
  177. if err != nil {
  178. log.Println("[MsgProxyConnect] ParseUrl:", err)
  179. c.Close(false)
  180. return
  181. }
  182. proxyConn, err := DailWithTimeout(c.hub.ctx, host, c.cf)
  183. if err != nil {
  184. log.Println("[MsgProxyConnect] DailWithTimeout:", err)
  185. // 发送失败状态包
  186. c.conn.WriteRawPackage(conn.ProxyResultPackageEncode(err.Error()), true)
  187. c.Close(false)
  188. return
  189. }
  190. c.proxyConn = proxyConn
  191. c.proxyHost = host
  192. c.SetState(StateProxied)
  193. // not news is good news
  194. c.conn.WriteRawPackage(conn.ProxyResultPackageEncode(""), true)
  195. go c.proxyDump()
  196. default:
  197. log.Println("[readPump] unknown msg:", msgType, id, cmd, state, string(data))
  198. }
  199. }
  200. }
  201. }
  202. // 代理情况下的消息转发
  203. // 会一直阻塞
  204. func (c *Line) proxyDump() {
  205. defer c.proxyConn.Close()
  206. for {
  207. if c.state == StateProxied && c.proxyConn != nil {
  208. buf, recycle, err := c.proxyConn.ReadRawPackage(c.cf.LongReadWait)
  209. if err != nil {
  210. if !strings.Contains(err.Error(), "EOF") {
  211. log.Println("[proxyDump] ReadRawPackage:", err)
  212. }
  213. c.Close(false)
  214. return
  215. }
  216. // 转发消息到代理端
  217. err = c.conn.WriteRawPackage(buf, recycle)
  218. if err != nil {
  219. log.Println("[proxyDump] WriteRawPackage:", err)
  220. return
  221. }
  222. } else if c.state == StateClosed || c.state == StateDisconnected {
  223. return
  224. } else {
  225. time.Sleep(time.Second)
  226. }
  227. }
  228. }
  229. // 检查管道并处理不同的消息,新go程调用
  230. // 为了防止多线程的冲突,主要的处理都在这里进行
  231. func (c *Line) writePump() {
  232. pingTicker := time.NewTicker(time.Duration(c.cf.PingInterval * int(time.Millisecond)))
  233. // 定义恢复函数
  234. defer func() {
  235. pingTicker.Stop()
  236. c.conn.Close()
  237. // 检查是否需要重新连接
  238. if c.autoReconnect && c.host != nil && c.state != StateClosed && c.state != StateConnected {
  239. go func() {
  240. defer func() {
  241. if err := recover(); err != nil {
  242. c.SetState(StateDisconnected)
  243. log.Println(err)
  244. debug.PrintStack()
  245. }
  246. }()
  247. c.host.Errors++
  248. c.host.Updated = time.Now()
  249. delay := 5 * time.Second * time.Duration(c.host.Errors)
  250. log.Println("[Line] will reconnect with delay:", delay)
  251. time.Sleep(delay)
  252. if c.host.Errors < 2 {
  253. c.hub.ConnectToServerX(c.channel, false, c.host)
  254. } else {
  255. c.hub.ConnectToServerX(c.channel, false, nil)
  256. }
  257. }()
  258. }
  259. }()
  260. // 清空closeConnect
  261. c.cleanClose()
  262. // 开始处理信息循环
  263. for {
  264. select {
  265. case request := <-c.sendRequest: // 发送请求包
  266. err := c.conn.WriteRequest(request.Id, request.Cmd, request.Data)
  267. if err != nil {
  268. log.Println("[writePump WriteRequest]", err)
  269. return
  270. }
  271. case response := <-c.sendResponse: // 接收到的响应包
  272. // 发送响应数据
  273. err := c.conn.WriteResponse(response.Id, response.State, response.Data)
  274. if err != nil {
  275. log.Println("[writePump WriteResponse]", err)
  276. return
  277. }
  278. case ping := <-c.pingRequest: // 发送ping包到网络
  279. if c.cf.PrintPing {
  280. log.Println("[PING]<-", c.channel, ping.Id)
  281. }
  282. // 只有服务器端需要回应ping包
  283. if c.host == nil {
  284. if c.cf.PrintPing {
  285. log.Println("[RESP PING]->", c.channel, ping.Id)
  286. }
  287. err := c.conn.WritePing(ping.Id)
  288. if err != nil {
  289. log.Println("[ping] failed", err)
  290. return
  291. }
  292. } else {
  293. // 检查 ping id 是否正确
  294. if c.pingID == ping.Id {
  295. c.pingWrongCount = 0
  296. } else {
  297. c.pingWrongCount++
  298. if c.pingWrongCount > 3 {
  299. log.Println("[wrong ping id]", ping.Id)
  300. c.Close(false)
  301. return
  302. }
  303. }
  304. }
  305. case <-pingTicker.C:
  306. // 检查是否已经很久时间没有使用连接了
  307. dr := time.Since(c.lastRead).Milliseconds()
  308. if dr > int64(c.cf.PingInterval)*5 {
  309. // 超时关闭当前的连接
  310. if c.cf.PrintMsg {
  311. log.Println("[Connect timeout]", c.channel)
  312. }
  313. // 有可能连接出现问题,断开并重新连接
  314. // if c.host != nil || c.proxyHost != nil {
  315. c.Close(false)
  316. return
  317. // }
  318. }
  319. // 只需要客户端发送
  320. if c.host != nil {
  321. // 发送ping包
  322. if dr >= int64(c.cf.PingInterval) {
  323. id := c.getPingID()
  324. // 发送ping数据包
  325. if c.cf.PrintPing {
  326. log.Println("[SEND PING]->", c.channel, id)
  327. }
  328. err := c.conn.WritePing(id)
  329. if err != nil {
  330. log.Println("[writePump WritePing]", err)
  331. return
  332. }
  333. }
  334. }
  335. case <-c.closeConnect:
  336. c.cleanClose()
  337. // 退出循环
  338. return
  339. }
  340. }
  341. }
  342. // 关闭连接
  343. func (c *Line) Close(quick bool) {
  344. defer recover() //避免管道已经关闭而引起panic
  345. c.conn.Close()
  346. if c.proxyConn != nil {
  347. c.proxyConn.Close()
  348. c.proxyConn = nil
  349. }
  350. c.proxyChannel = ""
  351. c.proxyHost = nil
  352. c.closeConnect <- quick
  353. if quick {
  354. c.SetState(StateClosed)
  355. c.hub.removeLine(c)
  356. } else if c.state != StateClosed {
  357. c.SetState(StateDisconnected)
  358. go c.hub.cleanDeadConnect()
  359. }
  360. c.Extra.Clear()
  361. // c.updated = time.Now()
  362. }
  363. // 清空余留下来的管道消息
  364. func (c *Line) cleanClose() {
  365. for {
  366. select {
  367. case <-c.closeConnect:
  368. default:
  369. return
  370. }
  371. }
  372. }
  373. // 连接开始运行
  374. func (c *Line) Start(channel string, conn conn.Connect, host *conn.HostInfo) {
  375. now := time.Now()
  376. // c.updated = now
  377. c.lastRead = now // 避免默认为0时被清理
  378. c.channel = channel
  379. c.conn = conn
  380. c.host = host
  381. if c.host != nil && c.proxyChannel != "" {
  382. // 进行代理连接
  383. c.SetState(StateProxing)
  384. err := c.hub.ClientProxyConnect(c, c.channel+"<-"+c.proxyChannel)
  385. if err != nil {
  386. log.Println("[ProxyConnect] error:", err)
  387. c.Close(false)
  388. } else {
  389. c.SetState(StateProxied)
  390. }
  391. go c.readPump()
  392. go c.writePump()
  393. } else {
  394. c.SetState(StateConnected)
  395. go c.readPump()
  396. go c.writePump()
  397. }
  398. }
  399. // 请求入口函数
  400. func NewConnect(
  401. cf *config.Config,
  402. hub *Hub,
  403. channel string,
  404. proxyChannel string,
  405. conn conn.Connect,
  406. host *conn.HostInfo,
  407. autoReconnect bool,
  408. ) *Line {
  409. now := time.Now()
  410. cc := &Line{
  411. cf: cf,
  412. channel: channel,
  413. hub: hub,
  414. pingID: uint16(now.UnixNano()) % config.ID_MAX,
  415. autoReconnect: autoReconnect,
  416. proxyChannel: proxyChannel,
  417. sendRequest: make(chan *RequestData, 32),
  418. sendResponse: make(chan *ResponseData, 32),
  419. pingRequest: make(chan *PingData, 5),
  420. closeConnect: make(chan bool, 5),
  421. lastRead: now, // 避免默认为0时被清理
  422. started: now,
  423. // updated: now,
  424. }
  425. cc.Start(channel, conn, host)
  426. return cc
  427. }