websocketTest.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package v1
  2. import (
  3. "bytes"
  4. "context"
  5. "designs/app/common/request"
  6. "designs/global"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/gin-gonic/gin"
  10. "github.com/gorilla/websocket"
  11. "github.com/vmihailenco/msgpack/v5"
  12. "io"
  13. "net/http"
  14. "strconv"
  15. "time"
  16. )
  17. func Websocket2(c *gin.Context) {
  18. //url := "192.168.1.139:9000/handle"
  19. url := "127.0.0.1:9000/handle"
  20. for i := 0; i <= 5000; i++ {
  21. time.Sleep(50 * time.Millisecond)
  22. go func() {
  23. openId := "1test00" + strconv.Itoa(i)
  24. time.Sleep(time.Millisecond)
  25. dial := "ws://" + url
  26. //fmt.Println(dial)
  27. c, _, err := websocket.DefaultDialer.Dial(dial, nil)
  28. if err != nil {
  29. global.App.Log.Error(err.Error())
  30. fmt.Println(err)
  31. }
  32. //defer c.Close()
  33. go func() {
  34. for {
  35. pong := ExplodeMsg(&MsgStruct{
  36. Type: MSG_TYPE_PING,
  37. Data: time.Now().UnixMilli(),
  38. })
  39. err = c.WriteMessage(websocket.TextMessage, pong)
  40. time.Sleep(time.Second * 10)
  41. }
  42. }()
  43. fmt.Println(openId, "登录成功,开始心跳")
  44. // 读取服务器的响应
  45. go ReadMsg(c)
  46. }()
  47. }
  48. }
  49. func Websocket(c *gin.Context) {
  50. form := request.Check(c, &struct {
  51. OpenId string `form:"openId" json:"openId" binding:""`
  52. }{})
  53. if form.OpenId == "" {
  54. form.OpenId = "1test00"
  55. }
  56. url := "127.0.0.1:8788"
  57. url = "lianliankan.ichunhao.cn"
  58. url = "nuoddzhise.ichunhao.cn"
  59. for i := 0; i <= 4000; i++ {
  60. openId := form.OpenId + strconv.Itoa(i)
  61. time.Sleep(time.Millisecond * 60)
  62. go TestWebsocket(openId, url)
  63. }
  64. //var i = 0
  65. //for {
  66. // openId := "1test00" + strconv.Itoa(i)
  67. // i++
  68. // time.Sleep(time.Millisecond)
  69. // go TestWebsocket(openId, url)
  70. // i++
  71. // go TestWebsocket(openId, url)
  72. //}
  73. }
  74. func Websocket1(c *gin.Context) {
  75. url := "dev1.ichunhao.cn"
  76. for i := 0; i <= 5000; i++ {
  77. openId := "1test00" + strconv.Itoa(i)
  78. time.Sleep(time.Millisecond * 10)
  79. go TestWebsocket(openId, url)
  80. }
  81. //var i = 0
  82. //for {
  83. // openId := "7test00" + strconv.Itoa(i)
  84. // i++
  85. // time.Sleep(time.Millisecond)
  86. // go TestWebsocket(openId)
  87. // i++
  88. // go TestWebsocket(openId)
  89. //}
  90. }
  91. func TestWebsocket(openId string, url string) {
  92. var token string
  93. //http://101.42.6.84:8787
  94. //http://127.0.0.1:8788 dev.ichunhao.cn
  95. gid := "tt_fpdz3"
  96. token = global.App.Redis.Get(context.Background(), openId+"userId").Val()
  97. if token == "" {
  98. //请求登录接口,获取token
  99. reportDat := map[string]string{
  100. "code": openId,
  101. "gid": gid,
  102. "pf": "web",
  103. }
  104. //请求接口获取token
  105. // /v1/user/getSysTime /v1/user/login
  106. content, err := CurlPost("http://"+url+"/v1/user/login", reportDat, nil)
  107. if err != nil {
  108. global.App.Log.Error(err.Error())
  109. fmt.Println(err)
  110. }
  111. var resp struct {
  112. Data struct {
  113. Token string `json:"token"`
  114. } `json:"data"`
  115. }
  116. str2oErr := json.Unmarshal([]byte(content), &resp)
  117. if str2oErr != nil {
  118. global.App.Log.Error(str2oErr.Error())
  119. fmt.Println(err)
  120. }
  121. if resp.Data.Token == "" {
  122. fmt.Println(content)
  123. }
  124. global.App.Redis.Set(context.Background(), openId+"userId", resp.Data.Token, time.Hour*3)
  125. token = resp.Data.Token
  126. //fmt.Println(content)
  127. }
  128. //fmt.Println(openId, "登录成功,开始心跳")
  129. //return
  130. //创建一个WebSocket客户端连接到服务器
  131. // 192.168.1.139:8788
  132. if token == "" {
  133. fmt.Println("token is empty")
  134. return
  135. }
  136. dial := "ws://" + url + "/v1/handle?token=" + token
  137. //fmt.Println(dial)
  138. c, _, err := websocket.DefaultDialer.Dial(dial, nil)
  139. if err != nil {
  140. global.App.Log.Error(err.Error())
  141. fmt.Println(err)
  142. }
  143. //defer c.Close()
  144. go func() {
  145. ////set_team
  146. //msg := ExplodeMsg(&MsgStruct{
  147. // Type: MSG_TYPE_SET_TEAM,
  148. // Data: 4,
  149. //})
  150. //err = c.WriteMessage(websocket.BinaryMessage, msg)
  151. //
  152. ////match
  153. //msg = ExplodeMsg(&MsgStruct{
  154. // Type: MSG_TYPE_MATCH,
  155. // Data: 2,
  156. //})
  157. //err = c.WriteMessage(websocket.TextMessage, msg)
  158. //
  159. //time.Sleep(time.Second * 10)
  160. ////MSG_TYPE_MATCH
  161. //
  162. //for i := 1; i <= 100; i++ {
  163. // msg = ExplodeMsg(&MsgStruct{
  164. // Type: MSG_TYPE_UPDATE_USER_GAMEDATA,
  165. // Data: map[string]interface{}{
  166. // "data": map[string]string{
  167. // "aa": "bbb",
  168. // "cc": "dddd",
  169. // },
  170. // "userKey": gid + "||web||" + openId,
  171. // },
  172. // })
  173. // //
  174. // //msg = ExplodeMsg(&MsgStruct{
  175. // // Type: MSG_TYPE_TALK,
  176. // // Data: "你好你好你好",
  177. // //})
  178. //
  179. // err = c.WriteMessage(websocket.BinaryMessage, msg)
  180. // time.Sleep(time.Second)
  181. //}
  182. //
  183. ////离开
  184. //msg = ExplodeMsg(&MsgStruct{
  185. // Type: MSG_TYPE_ROOM_EXIT,
  186. // Data: "",
  187. //})
  188. //err = c.WriteMessage(websocket.TextMessage, msg)
  189. for {
  190. pong := ExplodeMsg(&MsgStruct{
  191. Type: MSG_TYPE_PING,
  192. Data: time.Now().UnixMilli(),
  193. })
  194. err = c.WriteMessage(websocket.TextMessage, pong)
  195. time.Sleep(time.Second)
  196. }
  197. }()
  198. fmt.Println(openId, "登录成功,开始心跳")
  199. // 读取服务器的响应
  200. go ReadMsg(c)
  201. }
  202. type MsgStruct struct {
  203. Type string `msgpack:"type" json:"type"`
  204. Data interface{} `msgpack:"data" json:"data"`
  205. }
  206. func ExplodeMsg(msg *MsgStruct) []byte {
  207. //data, _ := json.Marshal(msg)
  208. data, _ := msgpack.Marshal(msg)
  209. return data
  210. }
  211. func ReadMsg(c *websocket.Conn) {
  212. for {
  213. _, _, err := c.ReadMessage()
  214. if err != nil {
  215. global.App.Log.Error(err.Error())
  216. fmt.Println(err)
  217. }
  218. //fmt.Printf("%s\n", message)
  219. }
  220. }
  221. func CurlPost(requestUrl string, requestBody interface{}, headerMap map[string]string) (string, error) {
  222. //转换json
  223. jsonBytes, err := json.Marshal(requestBody)
  224. if err != nil {
  225. return "", err
  226. }
  227. //创建请求
  228. req, err := http.NewRequest("POST", requestUrl, bytes.NewReader(jsonBytes))
  229. if err != nil {
  230. return "", err
  231. }
  232. //设置请求头
  233. req.Header.Set("Content-Type", "application/json;charset=UTF-8")
  234. for k, v := range headerMap {
  235. //req.Header.Set("Accept-Encoding", "gzip, deflate, br")
  236. req.Header.Set(k, v)
  237. }
  238. //发送请求
  239. clt := http.Client{Timeout: 60 * time.Second}
  240. res, err := clt.Do(req)
  241. if err != nil {
  242. return "", err
  243. }
  244. //获取结果
  245. body, err := io.ReadAll(res.Body)
  246. data := string(body)
  247. return data, err
  248. }
  249. const (
  250. MSG_TYPE_PING = "ping" //心跳
  251. MSG_TYPE_PONG = "pong" //心跳回传
  252. MSG_TYPE_TALK = "c2s_talk" //消息 -- 发送给所有人
  253. MSG_TYPE_TALK_RES = "s2c_talk" //消息 -- 服务端回发消息
  254. MSG_TYPE_MSG = "c2s_message" //消息 -- 发送给所有人
  255. MSG_TYPE_MSG_TO_HOST = "c2s_message_to_host" //消息 -- 发送给主机
  256. MSG_TYPE_MSG_WITHOUT_SELF = "c2s_message_without_self" //消息 -- 发送给除自己以外的人
  257. MSG_TYPE_EXIT = "exit" //退出
  258. MSG_TYPE_MATCH = "c2s_match" //开始匹配
  259. MSG_TYPE_SET_TEAM = "c2s_set_team" //创建组队
  260. MSG_TYPE_JOIN_TEAM = "c2s_join_team" //加入组队
  261. MSG_TYPE_EXIT_TEAM = "c2s_exit_team" //离开组队
  262. MSG_TYPE_LOGIN_SUCCESS = "s2c_login_success" //登录成功后,服务器回传给前端
  263. MSG_TYPE_MATCH_SUCCESS = "s2c_match_success" //匹配到对手后,提示匹配成功,加入房间
  264. MSG_TYPE_TEAM_SUCCESS = "s2c_team_success" //进入房间后,提示
  265. MSG_TYPE_MATCH_CANCEL = "c2s_match_cancel" //取消匹配
  266. MSG_TYPE_ROOM_EXIT = "c2s_room_exit" //用户离开房间
  267. MSG_TYPE_UPDATE_ROOM_GAMEDATA = "c2s_update_room_gameData" //更新房间的游戏信息
  268. MSG_TYPE_UPDATE_USER_GAMEDATA = "c2s_update_user_gameData" //更新用户的游戏信息
  269. MSG_TYPE_ROOM_GAMEDATA_CHANGE = "s2c_room_gameData_change" //房间游戏信息修改,广播给所有玩家
  270. MSG_TYPE_USER_GAMEDATA_CHANGE = "s2c_user_gameData_change" //房间游戏信息修改,广播给所有玩家
  271. MSG_TYPE_TEAM_USER_JOIN = "s2c_team_user_join" //队伍用户加入房间,通知其他人
  272. MSG_TYPE_TEAM_USER_EXIT = "s2c_team_user_exit" //队伍用户离开房间,通知其他人
  273. MSG_TYPE_USER_DISCONNECT = "s2c_user_disconnect" //队伍用户掉线,通知其他人
  274. MSG_TYPE_USER_RECONNECT = "s2c_user_reconnect" //队伍用户重连,通知其他人
  275. MSG_TYPE_TEAM_CHANGE_HOST = "s2c_team_change_host" //队伍更换房主
  276. MSG_TYPE_ROOM_CHANGE_HOST = "s2c_room_change_host" //房间更换房主
  277. MSG_TYPE_ERROR = "s2c_error" //有错误的时候专用
  278. MSG_TYPE_TEAM_JOIN_FAIL = "s2c_join_team_fail" //加入队伍失败时
  279. MSG_TYPE_TEAM_LEFT_FAIL = "s2c_left_team_fail" //离开队伍失败时
  280. MSG_TYPE_CLOSE_ROOM_FAIL = "s2c_close_room_fail" //关闭房间失败
  281. MSG_TYPE_USER_MATCH = "s2c_match" //用户进入匹配队列
  282. MSG_TYPE_USER_MATCH_CANCEL = "s2c_match_cancel" //用户离开匹配队列
  283. MSG_TYPE_KICK_OUT = "c2s_kick_out" //房主踢人出房间
  284. MSG_TYPE_READY = "c2s_ready" //准备开始
  285. MSG_TYPE_READY_RES = "s2c_ready" //准备开始回发
  286. MSG_TYPE_NOT_READY = "s2c_not_ready" //有人没准备
  287. MSG_TYPE_READY_CANCEL = "c2s_ready_cancel" //取消准备
  288. MSG_TYPE_READY_CANCEL_RES = "c2s_ready_cancel" //取消准备回发
  289. MSG_TYPE_CLOSE_ROOM = "c2s_close_room" //发送消息准备关闭房间
  290. MSG_TYPE_ROOM_CLOSED = "s2c_room_closed" //房间已关闭
  291. MSG_TYPE_EXIT_ROOM = "s2c_exit_room" //用户离开房间
  292. MSG_TYPE_TO_BACKED = "c2s_to_backed" //切换到后台
  293. MSG_TYPE_BACKED_RETURN = "c2s_backed_return" //从后台回来
  294. MSG_TYPE_SETTLEMENT = "s2c_settlement" //游戏结算消息
  295. MSG_TYPE_FINISH = "c2s_finish" //玩家完成游戏
  296. MSG_TYPE_FINISH_RES = "s2c_finish" //玩家完成游戏回发
  297. MSG_TYPE_RANK_DATA = "c2s_rank_data" //查询排行榜
  298. MSG_TYPE_RANK_DATA_RES = "s2c_rank_data" //查询排行榜回发
  299. MSG_TYPE_RECEIVE_REWARD = "c2s_receive_reward" //领取奖励
  300. MSG_TYPE_RECEIVE_REWARD_RES = "s2c_receive_reward"
  301. MSG_TYPE_SEASON = "c2s_season"
  302. MSG_TYPE_SEASON_RES = "s2c_season"
  303. )