hub.go 21 KB

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