hub.go 19 KB

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