line.go 10 KB

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