main.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/gorilla/websocket"
  7. "github.com/unrolled/secure"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var LocalPort = ":12080"
  14. var sslPort = ":12443"
  15. //设置接口没得到结果时的超时时间
  16. var OverTime = time.Second * 20
  17. type Clients struct {
  18. clientGroup string
  19. clientName string
  20. //Action map[string]string
  21. Data map[string]string
  22. clientWs *websocket.Conn
  23. }
  24. var upGrader = websocket.Upgrader{
  25. CheckOrigin: func(r *http.Request) bool { return true },
  26. }
  27. var hlClients sync.Map
  28. func NewClient(group string, name string, ws *websocket.Conn) *Clients {
  29. client := &Clients{
  30. clientGroup: group,
  31. clientName: name,
  32. Data: make(map[string]string),
  33. //Action: make(map[string]string),
  34. clientWs: ws,
  35. }
  36. return client
  37. }
  38. func ws(c *gin.Context) {
  39. getGroup, getName := c.Query("group"), c.Query("name")
  40. if getGroup == "" || getName == "" {
  41. return
  42. }
  43. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  44. if err != nil {
  45. fmt.Println("websocket err:", err)
  46. return
  47. }
  48. client := NewClient(getGroup, getName, ws)
  49. //message := []byte("hello," + getGroup + "->" + getName)
  50. //err = ws.WriteMessage(1, message)
  51. hlClients.Store(getGroup+"->"+getName, client)
  52. //defer ws.Close()
  53. for {
  54. //等待数据
  55. _, message, err := ws.ReadMessage()
  56. if err != nil {
  57. break
  58. }
  59. msg := string(message)
  60. check := []uint8{104, 108, 94, 95, 94}
  61. strIndex := strings.Index(msg, string(check))
  62. if strIndex >= 1 {
  63. action := msg[:strIndex]
  64. //fmt.Println(action,"save msg")
  65. //if client.Data[action] == "" {
  66. // client.Data[action] = msg[strIndex+5:]
  67. //}
  68. client.Data[action] = msg[strIndex+5:]
  69. fmt.Println("get_message:", client.Data[action])
  70. hlClients.Store(getGroup+"->"+getName, client)
  71. } else {
  72. fmt.Println(msg, "message error")
  73. }
  74. }
  75. defer ws.Close()
  76. }
  77. func QueryFunc(client *Clients, funcName string, param string) {
  78. var WriteDate string
  79. if param == "" {
  80. WriteDate = "{\"action\":\"" + funcName + "\"}"
  81. } else {
  82. WriteDate = "{\"action\":\"" + funcName + "\",\"param\":\"" + param + "\"}"
  83. }
  84. //fmt.Println(WriteDate, "writeDate")
  85. ws := client.clientWs
  86. err := ws.WriteMessage(1, []byte(WriteDate))
  87. if err != nil {
  88. fmt.Println(err, "写入数据失败")
  89. }
  90. }
  91. func Go(c *gin.Context) {
  92. getGroup, getName, Action, getParam := c.Query("group"), c.Query("name"), c.Query("action"), c.Query("param")
  93. if getGroup == "" || getName == "" {
  94. c.String(200, "input group and name")
  95. return
  96. }
  97. //fmt.Println(getGroup, getName)
  98. clientName, ok := hlClients.Load(getGroup + "->" + getName)
  99. //fmt.Println(clientName, "clientName")
  100. if ok == false {
  101. c.String(200, "注入了ws?没有找到当前组和名字")
  102. return
  103. }
  104. if Action == "" {
  105. c.JSON(200, gin.H{"group": getGroup, "name": getName})
  106. return
  107. }
  108. //取一个ws客户端
  109. client, ko := clientName.(*Clients)
  110. if !ko {
  111. return
  112. }
  113. //发送数据到web里得到结果
  114. QueryFunc(client, Action, getParam)
  115. //time.Sleep(time.Second)
  116. //data:=value.Action[getAction]
  117. ctx, cancel := context.WithTimeout(context.Background(), OverTime)
  118. for {
  119. select {
  120. case <-ctx.Done():
  121. // 获取链接超时了
  122. //fmt.Println("超时?")
  123. cancel()
  124. return
  125. default:
  126. data := client.Data[Action]
  127. //fmt.Println("正常中")
  128. if data != "" {
  129. cancel()
  130. //这里设置为空是为了清除上次的结果并且赋值判断
  131. client.Data[Action] = ""
  132. c.JSON(200, gin.H{"status": "200", "group": client.clientGroup, "name": client.clientName, Action: data})
  133. } else {
  134. time.Sleep(time.Millisecond * 500)
  135. }
  136. //else {
  137. // c.JSON(666, gin.H{"message": "?"})
  138. //}
  139. }
  140. }
  141. }
  142. func getList(c *gin.Context) {
  143. resList := "hliang:\r\n"
  144. hlClients.Range(func(key, value interface{}) bool {
  145. resList += key.(string) + "\r\n\t"
  146. return true
  147. })
  148. c.String(200, resList)
  149. }
  150. func Index(c *gin.Context) {
  151. c.String(200, "你好,我是黑脸怪~")
  152. }
  153. func TlsHandler() gin.HandlerFunc {
  154. return func(c *gin.Context) {
  155. secureMiddleware := secure.New(secure.Options{
  156. SSLRedirect: true,
  157. SSLHost: sslPort,
  158. })
  159. err := secureMiddleware.Process(c.Writer, c.Request)
  160. if err != nil {
  161. c.Abort()
  162. return
  163. }
  164. c.Next()
  165. }
  166. }
  167. func main() {
  168. //设置获取数据的超时时间30秒
  169. r := gin.Default()
  170. r.GET("/", Index)
  171. r.GET("/go", Go)
  172. r.GET("/ws", ws)
  173. r.GET("/list", getList)
  174. r.Use(TlsHandler())
  175. _ = r.Run(LocalPort)
  176. //_ = r.RunTLS(sslPort, "zhengshu.pem", "zhengshu.key")
  177. }