hub.go 24 KB

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