hub.go 24 KB

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