hub.go 21 KB

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