hub.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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*int(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. if h.cf.PrintMsg {
  242. log.Println("[SEND]->", conn.channel, "["+gd.Cmd+"]", subStr(string(gd.Data), 200))
  243. }
  244. count++
  245. if gd.Max > 0 && count >= gd.Max {
  246. return false
  247. }
  248. }
  249. return true
  250. })
  251. return
  252. }
  253. // 执行网络发送过来的命令
  254. func (h *Hub) requestFromNet(request *RequestData) {
  255. cmd := request.Cmd
  256. channel := request.conn.channel
  257. if h.cf.PrintMsg {
  258. log.Println("[REQU]<-", channel, "["+cmd+"]", subStr(string(request.Data), 200))
  259. }
  260. // 执行中间件
  261. for _, mdFunc := range h.middle {
  262. rsp := mdFunc(request)
  263. if rsp != nil {
  264. // NEXT_MIDDLE 表示当前的函数没有处理完成,还需要下个中间件处理
  265. if rsp.State == config.NEXT_MIDDLE {
  266. continue
  267. }
  268. // 返回消息
  269. if request.Id != 0 {
  270. rsp.Id = request.Id
  271. request.conn.sendResponse <- rsp
  272. }
  273. return
  274. } else {
  275. break
  276. }
  277. }
  278. sub, ok := h.subscribes.Load(cmd)
  279. if ok {
  280. subs := sub.([]*SubscribeData)
  281. // 倒序查找是为了新增的频道响应函数优先执行
  282. for i := len(subs) - 1; i >= 0; i-- {
  283. rg := subs[i]
  284. if rg.Channel.MatchString(channel) {
  285. state, data := rg.BackFunc(request)
  286. // NEXT_SUBSCRIBE 表示当前的函数没有处理完成,还需要下个注册函数处理
  287. if state == config.NEXT_SUBSCRIBE {
  288. continue
  289. }
  290. // 如果id为0表示不需要回应
  291. if request.Id != 0 {
  292. request.conn.sendResponse <- &ResponseData{
  293. Id: request.Id,
  294. State: state,
  295. Data: data,
  296. }
  297. if h.cf.PrintMsg {
  298. log.Println("[RESP]->", channel, "["+cmd+"]", state, subStr(string(data), 200))
  299. }
  300. }
  301. return
  302. }
  303. }
  304. }
  305. log.Println("[not match command]", channel, cmd)
  306. // 返回没有匹配的消息
  307. request.conn.sendResponse <- &ResponseData{
  308. Id: request.Id,
  309. State: config.NO_MATCH,
  310. Data: []byte(config.NO_MATCH_MSG),
  311. }
  312. }
  313. // 请求频道并获取数据,采用回调的方式返回结果
  314. // 当前调用将会阻塞,直到命令都执行结束,最后返回执行的数量
  315. // 如果 backFunc 返回为 false 则提前结束
  316. // 最大数量和超时时间如果为0的话表示使用默认值
  317. func (h *Hub) GetX(channel *regexp.Regexp, cmd string, data []byte, backFunc GetBack, max int, timeout int) (count int) {
  318. // 排除空频道
  319. if channel == nil {
  320. return 0
  321. }
  322. if timeout <= 0 {
  323. timeout = h.cf.ReadWait
  324. }
  325. gd := &GetData{
  326. Channel: channel,
  327. Cmd: cmd,
  328. Data: data,
  329. Max: max,
  330. Timeout: timeout,
  331. backchan: make(chan *ResponseData, 32),
  332. }
  333. sendMax := h.sendRequest(gd)
  334. if sendMax <= 0 {
  335. return 0
  336. }
  337. // 避免出现异常时线程无法退出
  338. timer := time.NewTimer(time.Millisecond * time.Duration(gd.Timeout+h.cf.WriteWait*2))
  339. defer func() {
  340. if !timer.Stop() {
  341. select {
  342. case <-timer.C:
  343. default:
  344. }
  345. }
  346. close(gd.backchan)
  347. }()
  348. for {
  349. select {
  350. case rp := <-gd.backchan:
  351. if rp == nil || rp.conn == nil {
  352. // 可能是已经退出了
  353. return
  354. }
  355. ch := rp.conn.channel
  356. if h.cf.PrintMsg {
  357. log.Println("[RECV]<-", ch, "["+gd.Cmd+"]", rp.State, subStr(string(rp.Data), 200))
  358. }
  359. count++
  360. // 如果这里返回为false这跳出循环
  361. if backFunc != nil && !backFunc(rp) {
  362. return
  363. }
  364. if count >= sendMax {
  365. return
  366. }
  367. case <-timer.C:
  368. return
  369. }
  370. }
  371. // return
  372. }
  373. // 请求频道并获取数据,采用回调的方式返回结果
  374. // 当前调用将会阻塞,直到命令都执行结束,最后返回执行的数量
  375. // 如果 backFunc 返回为 false 则提前结束
  376. func (h *Hub) Get(channel *regexp.Regexp, cmd string, data []byte, backFunc GetBack) (count int) {
  377. return h.GetX(channel, cmd, data, backFunc, 0, 0)
  378. }
  379. // 只获取一个频道的数据,阻塞等待到默认超时间隔
  380. // 如果没有结果将返回 NO_MATCH
  381. func (h *Hub) GetOne(channel *regexp.Regexp, cmd string, data []byte) (response *ResponseData) {
  382. h.GetX(channel, cmd, data, func(rp *ResponseData) (ok bool) {
  383. response = rp
  384. return false
  385. }, 1, 0)
  386. if response == nil {
  387. response = &ResponseData{
  388. State: config.NO_MATCH,
  389. Data: []byte(config.NO_MATCH_MSG),
  390. }
  391. }
  392. return
  393. }
  394. // 只获取一个频道的数据,阻塞等待到指定超时间隔
  395. // 如果没有结果将返回 NO_MATCH
  396. func (h *Hub) GetOneX(channel *regexp.Regexp, cmd string, data []byte, timeout int) (response *ResponseData) {
  397. h.GetX(channel, cmd, data, func(rp *ResponseData) (ok bool) {
  398. response = rp
  399. return false
  400. }, 1, timeout)
  401. if response == nil {
  402. response = &ResponseData{
  403. State: config.NO_MATCH,
  404. Data: []byte(config.NO_MATCH_MSG),
  405. }
  406. }
  407. return
  408. }
  409. // 推送消息出去,不需要返回数据
  410. func (h *Hub) Push(channel *regexp.Regexp, cmd string, data []byte) {
  411. // 排除空频道
  412. if channel == nil {
  413. return
  414. }
  415. gd := &GetData{
  416. Channel: channel,
  417. Cmd: cmd,
  418. Data: data,
  419. Timeout: h.cf.ReadWait,
  420. backchan: nil,
  421. }
  422. h.sendRequest(gd)
  423. }
  424. // 推送最大对应数量的消息出去,不需要返回数据
  425. func (h *Hub) PushX(channel *regexp.Regexp, cmd string, data []byte, max int) {
  426. // 排除空频道
  427. if channel == nil {
  428. return
  429. }
  430. gd := &GetData{
  431. Channel: channel,
  432. Cmd: cmd,
  433. Data: data,
  434. Max: max,
  435. Timeout: h.cf.ReadWait,
  436. backchan: nil,
  437. }
  438. h.sendRequest(gd)
  439. }
  440. // 增加连接
  441. func (h *Hub) addLine(line *Line) {
  442. if _, ok := h.connects.Load(line); ok {
  443. log.Println("connect have exist")
  444. // 连接已经存在,直接返回
  445. return
  446. }
  447. // 检查是否有相同的channel,如果有的话将其关闭删除
  448. channel := line.channel
  449. h.connects.Range(func(key, _ any) bool {
  450. conn := key.(*Line)
  451. // 删除超时的连接
  452. if conn.state != Connected && conn.host == nil && time.Since(conn.lastRead) > time.Duration(h.cf.PingInterval*5*int(time.Millisecond)) {
  453. h.connects.Delete(key)
  454. return true
  455. }
  456. if conn.channel == channel {
  457. conn.Close(true)
  458. h.connects.Delete(key)
  459. return false
  460. }
  461. return true
  462. })
  463. h.connects.Store(line, true)
  464. }
  465. // 删除连接
  466. func (h *Hub) removeLine(conn *Line) {
  467. conn.Close(true)
  468. h.connects.Delete(conn)
  469. }
  470. // 获取指定连接的连接持续时间
  471. func (h *Hub) ConnectDuration(conn *Line) time.Duration {
  472. t, ok := h.connects.Load(conn)
  473. if ok {
  474. return time.Since(t.(time.Time))
  475. }
  476. // 如果不存在直接返回0
  477. return time.Duration(0)
  478. }
  479. // 绑定端口,建立服务
  480. // 需要程序运行时调用
  481. func (h *Hub) BindForServer(info *HostInfo) (err error) {
  482. doConnectFunc := func(conn conn.Connect) {
  483. proto, version, channel, auth, err := conn.ReadAuthInfo()
  484. if err != nil {
  485. log.Println("[BindForServer ReadAuthInfo ERROR]", err)
  486. conn.Close()
  487. return
  488. }
  489. if version != info.Version || proto != info.Proto {
  490. log.Println("wrong version or protocol: ", version, proto)
  491. conn.Close()
  492. return
  493. }
  494. // 检查验证是否合法
  495. if !h.checkAuthFunc(proto, version, channel, auth) {
  496. conn.Close()
  497. return
  498. }
  499. // 发送频道信息
  500. if err := conn.WriteAuthInfo(h.channel, h.authFunc(proto, version, channel, auth)); err != nil {
  501. log.Println("[WriteAuthInfo ERROR]", err)
  502. conn.Close()
  503. return
  504. }
  505. // 将连接加入现有连接中
  506. done := false
  507. h.connects.Range(func(key, _ any) bool {
  508. line := key.(*Line)
  509. if line.state == Disconnected && line.channel == channel && line.host == nil {
  510. line.Start(conn, nil)
  511. done = true
  512. return false
  513. }
  514. return true
  515. })
  516. // 新建一个连接
  517. if !done {
  518. line := NewConnect(h.cf, h, channel, conn, nil)
  519. h.addLine(line)
  520. }
  521. }
  522. if info.Version == ws2.VERSION && info.Proto == ws2.PROTO {
  523. bind := ""
  524. if info.Bind != "" {
  525. bind = net.JoinHostPort(info.Bind, strconv.Itoa(int(info.Port)))
  526. }
  527. return ws2.Server(h.cf, bind, info.Path, info.Hash, doConnectFunc)
  528. } else if info.Version == tcp2.VERSION && info.Proto == tcp2.PROTO {
  529. return tcp2.Server(h.cf, net.JoinHostPort(info.Bind, strconv.Itoa(int(info.Port))), info.Hash, doConnectFunc)
  530. }
  531. return errors.New("not connect protocol and version found")
  532. }
  533. // 新建一个连接,不同的连接协议由底层自己选择
  534. // channel: 要连接的频道信息,需要能表达频道关键信息的部分
  535. func (h *Hub) ConnectToServer(channel string, force bool, host *HostInfo) (err error) {
  536. // 检查当前channel是否已经存在
  537. if !force {
  538. line := h.ChannelToLine(channel)
  539. if line != nil && line.state == Connected {
  540. err = fmt.Errorf("[ConnectToServer ERROR] existed channel: %s", channel)
  541. return
  542. }
  543. }
  544. if host == nil {
  545. // 获取服务地址等信息
  546. host, err = h.connectHostFunc(channel, Both)
  547. if err != nil {
  548. return err
  549. }
  550. }
  551. var conn conn.Connect
  552. var runProto string
  553. addr := net.JoinHostPort(host.Host, strconv.Itoa(int(host.Port)))
  554. // 添加定时器
  555. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(h.cf.ConnectTimeout))
  556. defer cancel()
  557. taskCh := make(chan bool)
  558. done := false
  559. go func() {
  560. if host.Version == ws2.VERSION && (host.Proto == ws2.PROTO || host.Proto == ws2.PROTO_STL) {
  561. runProto = ws2.PROTO
  562. conn, err = ws2.Dial(h.cf, host.Proto, addr, host.Path, host.Hash)
  563. } else if host.Version == tcp2.VERSION && host.Proto == tcp2.PROTO {
  564. runProto = tcp2.PROTO
  565. conn, err = tcp2.Dial(h.cf, addr, host.Hash)
  566. } else {
  567. err = fmt.Errorf("not correct protocol and version found in: %+v", host)
  568. }
  569. if done {
  570. if err != nil {
  571. log.Println("[Dial ERROR]", err)
  572. }
  573. if conn != nil {
  574. conn.Close()
  575. }
  576. } else {
  577. taskCh <- err == nil
  578. }
  579. }()
  580. select {
  581. case ok := <-taskCh:
  582. cancel()
  583. if !ok || err != nil || conn == nil {
  584. log.Println("[Client ERROR]", host.Proto, err)
  585. host.Errors++
  586. host.Updated = time.Now()
  587. if err == nil {
  588. err = errors.New("unknown error")
  589. }
  590. return err
  591. }
  592. case <-ctx.Done():
  593. done = true
  594. return errors.New("timeout")
  595. }
  596. // 发送验证信息
  597. if err := conn.WriteAuthInfo(h.channel, h.authFunc(runProto, host.Version, channel, nil)); err != nil {
  598. log.Println("[WriteAuthInfo ERROR]", err)
  599. conn.Close()
  600. host.Errors++
  601. host.Updated = time.Now()
  602. return err
  603. }
  604. // 接收频道信息
  605. proto, version, channel2, auth, err := conn.ReadAuthInfo()
  606. if err != nil {
  607. log.Println("[ConnectToServer ReadAuthInfo ERROR]", err)
  608. conn.Close()
  609. host.Errors++
  610. host.Updated = time.Now()
  611. return err
  612. }
  613. // 检查版本和协议是否一致
  614. if version != host.Version || proto != runProto {
  615. err = fmt.Errorf("[version or protocol wrong ERROR] %d, %s", version, proto)
  616. log.Println(err)
  617. conn.Close()
  618. host.Errors++
  619. host.Updated = time.Now()
  620. return err
  621. }
  622. // 检查频道名称是否匹配
  623. if !strings.Contains(channel2, channel) {
  624. err = fmt.Errorf("[channel ERROR] want %s, get %s", channel, channel2)
  625. log.Println(err)
  626. conn.Close()
  627. host.Errors++
  628. host.Updated = time.Now()
  629. return err
  630. }
  631. // 检查验证是否合法
  632. if !h.checkAuthFunc(proto, version, channel, auth) {
  633. err = fmt.Errorf("[checkAuthFunc ERROR] in proto: %s, version: %d, channel: %s, auth: %s", proto, version, channel, string(auth))
  634. log.Println(err)
  635. conn.Close()
  636. host.Errors++
  637. host.Updated = time.Now()
  638. return err
  639. }
  640. // 更新服务主机信息
  641. host.Errors = 0
  642. host.Updated = time.Now()
  643. // 将连接加入现有连接中
  644. done = false
  645. h.connects.Range(func(key, _ any) bool {
  646. line := key.(*Line)
  647. if line.channel == channel {
  648. if line.state == Connected {
  649. if force {
  650. line.Close(true)
  651. } else {
  652. err = fmt.Errorf("[connectToServer ERROR] channel already connected: %s", channel)
  653. log.Println(err)
  654. return false
  655. }
  656. }
  657. line.Start(conn, host)
  658. done = true
  659. return false
  660. }
  661. return true
  662. })
  663. if err != nil {
  664. return err
  665. }
  666. // 新建一个连接
  667. if !done {
  668. line := NewConnect(h.cf, h, channel, conn, host)
  669. h.addLine(line)
  670. }
  671. return nil
  672. }
  673. // 重试方式连接服务
  674. // 将会一直阻塞直到连接成功
  675. func (h *Hub) ConnectToServerX(channel string, force bool) {
  676. host, _ := h.connectHostFunc(channel, Direct)
  677. for {
  678. err := h.ConnectToServer(channel, force, host)
  679. if err == nil {
  680. return
  681. }
  682. host = nil
  683. log.Println("[ConnectToServer ERROR, try it again]", err)
  684. // 产生一个随机数避免刹间重连过载
  685. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  686. time.Sleep(time.Duration(r.Intn(h.cf.ConnectTimeout)+(h.cf.ConnectTimeout/2)) * time.Millisecond)
  687. }
  688. }
  689. // 检测处理代理连接
  690. func (h *Hub) checkProxyConnect() {
  691. if h.cf.ProxyTimeout <= 0 {
  692. return
  693. }
  694. proxyTicker := time.NewTicker(time.Duration(h.cf.ProxyTimeout * int(time.Millisecond)))
  695. for {
  696. <-proxyTicker.C
  697. now := time.Now().UnixMilli()
  698. h.connects.Range(func(key, _ any) bool {
  699. line := key.(*Line)
  700. if line.host != nil && line.host.Proxy && now-line.updated.UnixMilli() > int64(h.cf.ProxyTimeout) {
  701. host, err := h.connectHostFunc(line.channel, Direct)
  702. if err != nil {
  703. log.Println("[checkProxyConnect connectHostFunc ERROR]", err)
  704. return false
  705. }
  706. err = h.ConnectToServer(line.channel, true, host)
  707. if err != nil {
  708. log.Println("[checkProxyConnect ConnectToServer WARNING]", err)
  709. }
  710. }
  711. return true
  712. })
  713. }
  714. }
  715. // 建立一个集线器
  716. // connectFunc 用于监听连接状态的函数,可以为nil
  717. func NewHub(
  718. cf *config.Config,
  719. channel string,
  720. // 客户端需要用的函数
  721. connectHostFunc ConnectHostFunc,
  722. authFunc AuthFunc,
  723. // 服务端需要用的函数
  724. checkAuthFunc CheckAuthFunc,
  725. // 连接状态变化时调用的函数
  726. connectStatusFunc ConnectStatusFunc,
  727. ) (h *Hub) {
  728. h = &Hub{
  729. cf: cf,
  730. channel: channel,
  731. middle: make([]MiddleFunc, 0),
  732. connectHostFunc: connectHostFunc,
  733. authFunc: authFunc,
  734. checkAuthFunc: checkAuthFunc,
  735. connectStatusFunc: connectStatusFunc,
  736. lastCleanDeadConnect: time.Now().UnixMilli(),
  737. }
  738. go h.checkProxyConnect()
  739. return h
  740. }