hub.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. package tinymq
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "math/rand"
  8. "net"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "git.me9.top/git/tinymq/config"
  15. "git.me9.top/git/tinymq/conn"
  16. "git.me9.top/git/tinymq/conn/tcp2"
  17. "git.me9.top/git/tinymq/conn/ws2"
  18. )
  19. // 类似一个插座的功能,管理多个连接
  20. // 一个hub即可以是客户端,同时也可以是服务端
  21. // 为了简化流程和让通讯更加迅速,不再重发和缓存结果,采用超时的方式告诉应用层。
  22. // 截取部分字符串
  23. func subStr(str string, length int) string {
  24. if len(str) <= length {
  25. return str
  26. }
  27. return str[0:length] + "..."
  28. }
  29. type Hub struct {
  30. sync.Mutex
  31. cf *config.Config
  32. globalID uint16
  33. channel string // 本地频道信息
  34. middle []MiddleFunc // 中间件
  35. connects sync.Map // map[*Line]bool(true) //记录当前的连接,方便查找
  36. subscribes sync.Map // [cmd]->[]*SubscribeData //注册绑定频道的函数,用于响应请求
  37. msgCache sync.Map // map[uint16]*GetMsg //请求的回应记录,key为id
  38. // 客户端需要用的函数
  39. connectHostFunc ConnectHostFunc // 获取对应频道的一个连接地址
  40. authFunc AuthFunc // 获取认证信息,用于发送给对方
  41. // 服务端需要用的函数
  42. checkAuthFunc CheckAuthFunc // 核对认证是否合法
  43. // 连接状态变化时调用的函数
  44. connectStatusFunc ConnectStatusFunc
  45. // 上次清理异常连接时间戳
  46. lastCleanDeadConnect int64
  47. }
  48. // 清理异常连接
  49. func (h *Hub) cleanDeadConnect() {
  50. h.Lock()
  51. defer h.Unlock()
  52. now := time.Now().UnixMilli()
  53. if now-h.lastCleanDeadConnect > int64(h.cf.CleanDeadConnectWait) {
  54. h.lastCleanDeadConnect = now
  55. h.connects.Range(func(key, _ any) bool {
  56. line := key.(*Line)
  57. if line.state != Connected && now-line.updated.UnixMilli() > int64(h.cf.CleanDeadConnectWait) {
  58. h.connects.Delete(key)
  59. }
  60. return true
  61. })
  62. }
  63. }
  64. // 获取通讯消息ID号
  65. func (h *Hub) GetID() uint16 {
  66. h.Lock()
  67. defer h.Unlock()
  68. h.globalID++
  69. if h.globalID <= 0 || h.globalID >= config.ID_MAX {
  70. h.globalID = 1
  71. }
  72. for {
  73. // 检查是否在请求队列中存在对应的id
  74. if _, ok := h.msgCache.Load(h.globalID); ok {
  75. h.globalID++
  76. if h.globalID <= 0 || h.globalID >= config.ID_MAX {
  77. h.globalID = 1
  78. }
  79. } else {
  80. break
  81. }
  82. }
  83. return h.globalID
  84. }
  85. // 添加中间件
  86. func (h *Hub) UseMiddle(middleFunc MiddleFunc) {
  87. h.middle = append(h.middle, middleFunc)
  88. }
  89. // 注册频道,其中频道为正则表达式字符串
  90. func (h *Hub) Subscribe(channel *regexp.Regexp, cmd string, backFunc SubscribeBack) (err error) {
  91. if channel == nil {
  92. return errors.New("channel can not be nil")
  93. }
  94. reg := &SubscribeData{
  95. Channel: channel,
  96. Cmd: cmd,
  97. BackFunc: backFunc,
  98. }
  99. sub, ok := h.subscribes.Load(cmd)
  100. if ok {
  101. h.subscribes.Store(cmd, append(sub.([]*SubscribeData), reg))
  102. return
  103. }
  104. regs := make([]*SubscribeData, 1)
  105. regs[0] = reg
  106. h.subscribes.Store(cmd, regs)
  107. return
  108. }
  109. // 获取当前在线的数量
  110. func (h *Hub) ConnectNum() int {
  111. var count int
  112. h.connects.Range(func(key, _ any) bool {
  113. if key.(*Line).state == Connected {
  114. count++
  115. }
  116. return true
  117. })
  118. return count
  119. }
  120. // 获取所有的在线连接频道
  121. func (h *Hub) AllChannel() []string {
  122. cs := make([]string, 0)
  123. h.connects.Range(func(key, _ any) bool {
  124. line := key.(*Line)
  125. if line.state == Connected {
  126. cs = append(cs, line.channel)
  127. }
  128. return true
  129. })
  130. return cs
  131. }
  132. // 获取所有连接频道和连接时长
  133. // 为了避免定义数据结构麻烦,采用|隔开
  134. func (h *Hub) AllChannelTime() []string {
  135. cs := make([]string, 0)
  136. h.connects.Range(func(key, value any) bool {
  137. line := key.(*Line)
  138. if line.state == Connected {
  139. ti := time.Since(value.(time.Time)).Milliseconds()
  140. cs = append(cs, line.channel+"|"+strconv.FormatInt(ti, 10))
  141. }
  142. return true
  143. })
  144. return cs
  145. }
  146. // 获取频道并通过函数过滤,如果返回 false 将终止
  147. func (h *Hub) ChannelToFunc(fn func(string) bool) {
  148. h.connects.Range(func(key, _ any) bool {
  149. line := key.(*Line)
  150. if line.state == Connected {
  151. return fn(line.channel)
  152. }
  153. return true
  154. })
  155. }
  156. // 从 channel 获取连接
  157. func (h *Hub) ChannelToLine(channel string) (line *Line) {
  158. h.connects.Range(func(key, _ any) bool {
  159. l := key.(*Line)
  160. if l.channel == channel {
  161. line = l
  162. return false
  163. }
  164. return true
  165. })
  166. return
  167. }
  168. // 返回请求结果
  169. func (h *Hub) outResponse(response *ResponseData) {
  170. defer recover() //避免管道已经关闭而引起panic
  171. id := response.Id
  172. t, ok := h.msgCache.Load(id)
  173. if ok {
  174. // 删除数据缓存
  175. h.msgCache.Delete(id)
  176. gm := t.(*GetMsg)
  177. // 停止定时器
  178. if !gm.timer.Stop() {
  179. select {
  180. case <-gm.timer.C:
  181. default:
  182. }
  183. }
  184. // 回应数据到上层
  185. gm.out <- response
  186. }
  187. }
  188. // 发送数据到网络接口
  189. // 返回发送的数量
  190. func (h *Hub) sendRequest(gd *GetData) (count int) {
  191. h.connects.Range(func(key, _ any) bool {
  192. conn := key.(*Line)
  193. // 检查连接是否OK
  194. if conn.state != Connected {
  195. return true
  196. }
  197. if gd.Channel.MatchString(conn.channel) {
  198. var id uint16
  199. if gd.backchan != nil {
  200. id = h.GetID()
  201. timeout := gd.Timeout
  202. if timeout <= 0 {
  203. timeout = h.cf.WriteWait
  204. }
  205. fn := func(id uint16, conn *Line) func() {
  206. return func() {
  207. go h.outResponse(&ResponseData{
  208. Id: id,
  209. State: config.GET_TIMEOUT,
  210. Data: []byte(config.GET_TIMEOUT_MSG),
  211. conn: conn,
  212. })
  213. // 检查是否已经很久时间没有使用连接了
  214. if time.Since(conn.lastRead) > time.Duration(h.cf.PingInterval*3)*time.Millisecond {
  215. // 超时关闭当前的连接
  216. log.Println("get message timeout", conn.channel)
  217. // 有可能连接出现问题,断开并重新连接
  218. conn.Close(false)
  219. return
  220. }
  221. }
  222. }(id, conn)
  223. // 将要发送的请求缓存
  224. gm := &GetMsg{
  225. out: gd.backchan,
  226. timer: time.AfterFunc(time.Millisecond*time.Duration(timeout), fn),
  227. }
  228. h.msgCache.Store(id, gm)
  229. }
  230. // 组织数据并发送到Connect
  231. conn.sendRequest <- &RequestData{
  232. Id: id,
  233. Cmd: gd.Cmd,
  234. Data: gd.Data,
  235. timeout: gd.Timeout,
  236. backchan: gd.backchan,
  237. conn: conn,
  238. }
  239. log.Println("[SEND]->", conn.channel, "["+gd.Cmd+"]", subStr(string(gd.Data), 200))
  240. count++
  241. if gd.Max > 0 && count >= gd.Max {
  242. return false
  243. }
  244. }
  245. return true
  246. })
  247. return
  248. }
  249. // 执行网络发送过来的命令
  250. func (h *Hub) requestFromNet(request *RequestData) {
  251. cmd := request.Cmd
  252. channel := request.conn.channel
  253. log.Println("[REQU]<-", channel, "["+cmd+"]", subStr(string(request.Data), 200))
  254. // 执行中间件
  255. for _, mdFunc := range h.middle {
  256. rsp := mdFunc(request)
  257. if rsp != nil {
  258. if request.Id != 0 {
  259. rsp.Id = request.Id
  260. request.conn.sendResponse <- rsp
  261. }
  262. return
  263. }
  264. }
  265. sub, ok := h.subscribes.Load(cmd)
  266. if ok {
  267. subs := sub.([]*SubscribeData)
  268. // 倒序查找是为了新增的频道响应函数优先执行
  269. for i := len(subs) - 1; i >= 0; i-- {
  270. rg := subs[i]
  271. if rg.Channel.MatchString(channel) {
  272. state, data := rg.BackFunc(request)
  273. // NEXT_SUBSCRIBE 表示当前的函数没有处理完成,还需要下个注册函数处理
  274. if state == config.NEXT_SUBSCRIBE {
  275. continue
  276. }
  277. // 如果id为0表示不需要回应
  278. if request.Id != 0 {
  279. request.conn.sendResponse <- &ResponseData{
  280. Id: request.Id,
  281. State: state,
  282. Data: data,
  283. }
  284. log.Println("[RESP]->", channel, "["+cmd+"]", state, subStr(string(data), 200))
  285. }
  286. return
  287. }
  288. }
  289. }
  290. log.Println("[not match command]", channel, cmd)
  291. // 返回没有匹配的消息
  292. request.conn.sendResponse <- &ResponseData{
  293. Id: request.Id,
  294. State: config.NO_MATCH,
  295. Data: []byte(config.NO_MATCH_MSG),
  296. }
  297. }
  298. // 请求频道并获取数据,采用回调的方式返回结果
  299. // 当前调用将会阻塞,直到命令都执行结束,最后返回执行的数量
  300. // 如果 backFunc 返回为 false 则提前结束
  301. // 最大数量和超时时间如果为0的话表示使用默认值
  302. func (h *Hub) GetX(channel *regexp.Regexp, cmd string, data []byte, backFunc GetBack, max int, timeout int) (count int) {
  303. // 排除空频道
  304. if channel == nil {
  305. return 0
  306. }
  307. if timeout <= 0 {
  308. timeout = h.cf.ReadWait
  309. }
  310. gd := &GetData{
  311. Channel: channel,
  312. Cmd: cmd,
  313. Data: data,
  314. Max: max,
  315. Timeout: timeout,
  316. backchan: make(chan *ResponseData, 32),
  317. }
  318. sendMax := h.sendRequest(gd)
  319. if sendMax <= 0 {
  320. return 0
  321. }
  322. // 避免出现异常时线程无法退出
  323. timer := time.NewTimer(time.Millisecond * time.Duration(gd.Timeout+h.cf.WriteWait*2))
  324. defer func() {
  325. if !timer.Stop() {
  326. select {
  327. case <-timer.C:
  328. default:
  329. }
  330. }
  331. close(gd.backchan)
  332. }()
  333. for {
  334. select {
  335. case rp := <-gd.backchan:
  336. if rp == nil || rp.conn == nil {
  337. // 可能是已经退出了
  338. return
  339. }
  340. ch := rp.conn.channel
  341. log.Println("[RECV]<-", ch, "["+gd.Cmd+"]", rp.State, subStr(string(rp.Data), 200))
  342. count++
  343. // 如果这里返回为false这跳出循环
  344. if backFunc != nil && !backFunc(rp) {
  345. return
  346. }
  347. if count >= sendMax {
  348. return
  349. }
  350. case <-timer.C:
  351. return
  352. }
  353. }
  354. // return
  355. }
  356. // 请求频道并获取数据,采用回调的方式返回结果
  357. // 当前调用将会阻塞,直到命令都执行结束,最后返回执行的数量
  358. // 如果 backFunc 返回为 false 则提前结束
  359. func (h *Hub) Get(channel *regexp.Regexp, cmd string, data []byte, backFunc GetBack) (count int) {
  360. return h.GetX(channel, cmd, data, backFunc, 0, 0)
  361. }
  362. // 只获取一个频道的数据,阻塞等待到默认超时间隔
  363. // 如果没有结果将返回 NO_MATCH
  364. func (h *Hub) GetOne(channel *regexp.Regexp, cmd string, data []byte) (response *ResponseData) {
  365. h.GetX(channel, cmd, data, func(rp *ResponseData) (ok bool) {
  366. response = rp
  367. return false
  368. }, 1, 0)
  369. if response == nil {
  370. response = &ResponseData{
  371. State: config.NO_MATCH,
  372. Data: []byte(config.NO_MATCH_MSG),
  373. }
  374. }
  375. return
  376. }
  377. // 只获取一个频道的数据,阻塞等待到指定超时间隔
  378. // 如果没有结果将返回 NO_MATCH
  379. func (h *Hub) GetOneX(channel *regexp.Regexp, cmd string, data []byte, timeout int) (response *ResponseData) {
  380. h.GetX(channel, cmd, data, func(rp *ResponseData) (ok bool) {
  381. response = rp
  382. return false
  383. }, 1, timeout)
  384. if response == nil {
  385. response = &ResponseData{
  386. State: config.NO_MATCH,
  387. Data: []byte(config.NO_MATCH_MSG),
  388. }
  389. }
  390. return
  391. }
  392. // 推送消息出去,不需要返回数据
  393. func (h *Hub) Push(channel *regexp.Regexp, cmd string, data []byte) {
  394. // 排除空频道
  395. if channel == nil {
  396. return
  397. }
  398. gd := &GetData{
  399. Channel: channel,
  400. Cmd: cmd,
  401. Data: data,
  402. Timeout: h.cf.ReadWait,
  403. backchan: nil,
  404. }
  405. h.sendRequest(gd)
  406. }
  407. // 推送最大对应数量的消息出去,不需要返回数据
  408. func (h *Hub) PushX(channel *regexp.Regexp, cmd string, data []byte, max int) {
  409. // 排除空频道
  410. if channel == nil {
  411. return
  412. }
  413. gd := &GetData{
  414. Channel: channel,
  415. Cmd: cmd,
  416. Data: data,
  417. Max: max,
  418. Timeout: h.cf.ReadWait,
  419. backchan: nil,
  420. }
  421. h.sendRequest(gd)
  422. }
  423. // 增加连接
  424. func (h *Hub) addLine(line *Line) {
  425. if _, ok := h.connects.Load(line); ok {
  426. log.Println("connect have exist")
  427. // 连接已经存在,直接返回
  428. return
  429. }
  430. // 检查是否有相同的channel,如果有的话将其关闭删除
  431. channel := line.channel
  432. h.connects.Range(func(key, _ any) bool {
  433. conn := key.(*Line)
  434. // 删除超时的连接
  435. if conn.state != Connected && conn.host == nil && time.Since(conn.lastRead) > time.Duration(h.cf.PingInterval*5)*time.Millisecond {
  436. h.connects.Delete(key)
  437. return true
  438. }
  439. if conn.channel == channel {
  440. conn.Close(true)
  441. h.connects.Delete(key)
  442. return false
  443. }
  444. return true
  445. })
  446. h.connects.Store(line, true)
  447. }
  448. // 删除连接
  449. func (h *Hub) removeLine(conn *Line) {
  450. conn.Close(true)
  451. h.connects.Delete(conn)
  452. }
  453. // 获取指定连接的连接持续时间
  454. func (h *Hub) ConnectDuration(conn *Line) time.Duration {
  455. t, ok := h.connects.Load(conn)
  456. if ok {
  457. return time.Since(t.(time.Time))
  458. }
  459. // 如果不存在直接返回0
  460. return time.Duration(0)
  461. }
  462. // 绑定端口,建立服务
  463. // 需要程序运行时调用
  464. func (h *Hub) BindForServer(info *HostInfo) (err error) {
  465. doConnectFunc := func(conn conn.Connect) {
  466. proto, version, channel, auth, err := conn.ReadAuthInfo()
  467. if err != nil {
  468. log.Println("[BindForServer ReadAuthInfo ERROR]", err)
  469. conn.Close()
  470. return
  471. }
  472. if version != info.Version || proto != info.Proto {
  473. log.Println("wrong version or protocol: ", version, proto)
  474. conn.Close()
  475. return
  476. }
  477. // 检查验证是否合法
  478. if !h.checkAuthFunc(proto, version, channel, auth) {
  479. conn.Close()
  480. return
  481. }
  482. // 发送频道信息
  483. if err := conn.WriteAuthInfo(h.channel, h.authFunc(proto, version, channel, auth)); err != nil {
  484. log.Println("[WriteAuthInfo ERROR]", err)
  485. conn.Close()
  486. return
  487. }
  488. // 将连接加入现有连接中
  489. done := false
  490. h.connects.Range(func(key, _ any) bool {
  491. line := key.(*Line)
  492. if line.state == Disconnected && line.channel == channel && line.host == nil {
  493. line.Start(conn, nil)
  494. done = true
  495. return false
  496. }
  497. return true
  498. })
  499. // 新建一个连接
  500. if !done {
  501. line := NewConnect(h.cf, h, channel, conn, nil)
  502. h.addLine(line)
  503. }
  504. }
  505. if info.Version == ws2.VERSION && info.Proto == ws2.PROTO {
  506. bind := ""
  507. if info.Bind != "" {
  508. bind = net.JoinHostPort(info.Bind, strconv.Itoa(int(info.Port)))
  509. }
  510. return ws2.Server(h.cf, bind, info.Path, info.Hash, doConnectFunc)
  511. } else if info.Version == tcp2.VERSION && info.Proto == tcp2.PROTO {
  512. return tcp2.Server(h.cf, net.JoinHostPort(info.Bind, strconv.Itoa(int(info.Port))), info.Hash, doConnectFunc)
  513. }
  514. return errors.New("not connect protocol and version found")
  515. }
  516. // 新建一个连接,不同的连接协议由底层自己选择
  517. // channel: 要连接的频道信息,需要能表达频道关键信息的部分
  518. func (h *Hub) ConnectToServer(channel string, force bool) (err error) {
  519. // 检查当前channel是否已经存在
  520. if !force {
  521. line := h.ChannelToLine(channel)
  522. if line != nil && line.state == Connected {
  523. err = fmt.Errorf("[ConnectToServer ERROR] existed channel: %s", channel)
  524. return
  525. }
  526. }
  527. // 获取服务地址等信息
  528. host, err := h.connectHostFunc(channel)
  529. if err != nil {
  530. return err
  531. }
  532. var conn conn.Connect
  533. var runProto string
  534. addr := net.JoinHostPort(host.Host, strconv.Itoa(int(host.Port)))
  535. // 添加定时器
  536. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(h.cf.ConnectTimeout))
  537. defer cancel()
  538. taskCh := make(chan bool)
  539. done := false
  540. go func() {
  541. if host.Version == ws2.VERSION && (host.Proto == ws2.PROTO || host.Proto == ws2.PROTO_STL) {
  542. runProto = ws2.PROTO
  543. conn, err = ws2.Dial(h.cf, host.Proto, addr, host.Path, host.Hash)
  544. } else if host.Version == tcp2.VERSION && host.Proto == tcp2.PROTO {
  545. runProto = tcp2.PROTO
  546. conn, err = tcp2.Dial(h.cf, addr, host.Hash)
  547. } else {
  548. err = fmt.Errorf("not correct protocol and version found in: %+v", host)
  549. }
  550. if done {
  551. if err != nil {
  552. log.Println("[Dial ERROR]", err)
  553. }
  554. if conn != nil {
  555. conn.Close()
  556. }
  557. } else {
  558. taskCh <- err == nil
  559. }
  560. }()
  561. select {
  562. case ok := <-taskCh:
  563. cancel()
  564. if !ok || err != nil || conn == nil {
  565. log.Println("[Client ERROR]", host.Proto, err)
  566. host.Errors++
  567. host.Updated = time.Now()
  568. if err == nil {
  569. err = errors.New("unknown error")
  570. }
  571. return err
  572. }
  573. case <-ctx.Done():
  574. done = true
  575. return errors.New("timeout")
  576. }
  577. // 发送验证信息
  578. if err := conn.WriteAuthInfo(h.channel, h.authFunc(runProto, host.Version, channel, nil)); err != nil {
  579. log.Println("[WriteAuthInfo ERROR]", err)
  580. conn.Close()
  581. host.Errors++
  582. host.Updated = time.Now()
  583. return err
  584. }
  585. // 接收频道信息
  586. proto, version, channel2, auth, err := conn.ReadAuthInfo()
  587. if err != nil {
  588. log.Println("[ConnectToServer ReadAuthInfo ERROR]", err)
  589. conn.Close()
  590. host.Errors++
  591. host.Updated = time.Now()
  592. return err
  593. }
  594. // 检查版本和协议是否一致
  595. if version != host.Version || proto != runProto {
  596. err = fmt.Errorf("[version or protocol wrong ERROR] %d, %s", version, proto)
  597. log.Println(err)
  598. conn.Close()
  599. host.Errors++
  600. host.Updated = time.Now()
  601. return err
  602. }
  603. // 检查频道名称是否匹配
  604. if !strings.Contains(channel2, channel) {
  605. err = fmt.Errorf("[channel ERROR] want %s, get %s", channel, channel2)
  606. log.Println(err)
  607. conn.Close()
  608. host.Errors++
  609. host.Updated = time.Now()
  610. return err
  611. }
  612. // 检查验证是否合法
  613. if !h.checkAuthFunc(proto, version, channel, auth) {
  614. err = fmt.Errorf("[checkAuthFunc ERROR] in proto: %s, version: %d, channel: %s, auth: %s", proto, version, channel, string(auth))
  615. log.Println(err)
  616. conn.Close()
  617. host.Errors++
  618. host.Updated = time.Now()
  619. return err
  620. }
  621. // 更新服务主机信息
  622. host.Errors = 0
  623. host.Updated = time.Now()
  624. // 将连接加入现有连接中
  625. done = false
  626. h.connects.Range(func(key, _ any) bool {
  627. line := key.(*Line)
  628. if line.channel == channel {
  629. if line.state == Connected {
  630. if !force {
  631. err = fmt.Errorf("[connectToServer ERROR] channel already connected: %s", channel)
  632. log.Println(err)
  633. return false
  634. }
  635. return true
  636. }
  637. line.Start(conn, host)
  638. done = true
  639. return false
  640. }
  641. return true
  642. })
  643. if err != nil {
  644. return err
  645. }
  646. // 新建一个连接
  647. if !done {
  648. line := NewConnect(h.cf, h, channel, conn, host)
  649. h.addLine(line)
  650. }
  651. return nil
  652. }
  653. // 重试方式连接服务
  654. // 将会一直阻塞直到连接成功
  655. func (h *Hub) ConnectToServerX(channel string, force bool) {
  656. for {
  657. err := h.ConnectToServer(channel, force)
  658. if err == nil {
  659. return
  660. }
  661. log.Println("[ConnectToServer ERROR, try it again]", err)
  662. // 产生一个随机数避免刹间重连过载
  663. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  664. time.Sleep(time.Duration(r.Intn(h.cf.ConnectTimeout)+(h.cf.ConnectTimeout/2)) * time.Millisecond)
  665. }
  666. }
  667. // 建立一个集线器
  668. // connectFunc 用于监听连接状态的函数,可以为nil
  669. func NewHub(
  670. cf *config.Config,
  671. channel string,
  672. // 客户端需要用的函数
  673. connectHostFunc ConnectHostFunc,
  674. authFunc AuthFunc,
  675. // 服务端需要用的函数
  676. checkAuthFunc CheckAuthFunc,
  677. // 连接状态变化时调用的函数
  678. connectStatusFunc ConnectStatusFunc,
  679. ) (h *Hub) {
  680. h = &Hub{
  681. cf: cf,
  682. channel: channel,
  683. middle: make([]MiddleFunc, 0),
  684. connectHostFunc: connectHostFunc,
  685. authFunc: authFunc,
  686. checkAuthFunc: checkAuthFunc,
  687. connectStatusFunc: connectStatusFunc,
  688. lastCleanDeadConnect: time.Now().UnixMilli(),
  689. }
  690. return h
  691. }