engine.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package core
  2. import (
  3. "JsRpc/config"
  4. "JsRpc/utils"
  5. "encoding/json"
  6. "fmt"
  7. "math/rand"
  8. "time"
  9. )
  10. // GQueryFunc 发送请求到客户端
  11. func (c *Clients) GQueryFunc(funcName string, param string, resChan chan<- string) {
  12. MessageId := utils.GetUUID()
  13. WriteData := Message{Param: param, MessageId: MessageId, Action: funcName}
  14. data, _ := json.Marshal(WriteData)
  15. clientWs := c.clientWs
  16. gm.Lock()
  17. // 先判断action是否需要初始化
  18. if c.actionData[funcName] == nil {
  19. c.actionData[funcName] = make(map[string]chan string)
  20. }
  21. if c.actionData[funcName][MessageId] == nil {
  22. c.actionData[funcName][MessageId] = make(chan string, 1) //此次action初始化1个消息
  23. }
  24. err := clientWs.WriteMessage(1, data)
  25. gm.Unlock()
  26. if err != nil {
  27. fmt.Println(err, "写入数据失败")
  28. }
  29. select {
  30. case res := <-c.actionData[funcName][MessageId]:
  31. resChan <- res
  32. case <-time.After(time.Duration(config.DefaultTimeout) * time.Second):
  33. resChan <- "黑脸怪:timeout"
  34. }
  35. // 清理资源
  36. gm.Lock()
  37. delete(c.actionData[funcName], MessageId)
  38. gm.Unlock()
  39. close(resChan)
  40. }
  41. func getRandomClient(group string, clientId string) *Clients {
  42. var client *Clients
  43. // 不传递clientId时候,从group分组随便拿一个
  44. if clientId != "" {
  45. clientName, ok := hlSyncMap.Load(group + "->" + clientId)
  46. if ok == false {
  47. return nil
  48. }
  49. client, _ = clientName.(*Clients)
  50. return client
  51. }
  52. groupClients := make([]*Clients, 0)
  53. //循环读取syncMap 获取group名字的
  54. hlSyncMap.Range(func(_, value interface{}) bool {
  55. tmpClients, ok := value.(*Clients)
  56. if !ok {
  57. return true
  58. }
  59. if tmpClients.clientGroup == group {
  60. groupClients = append(groupClients, tmpClients)
  61. }
  62. return true
  63. })
  64. if len(groupClients) == 0 {
  65. return nil
  66. }
  67. // 使用随机数发生器
  68. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  69. randomIndex := r.Intn(len(groupClients))
  70. client = groupClients[randomIndex]
  71. return client
  72. }