chatWs.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package controller
  2. import (
  3. "aiChat/internal/model"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. "github.com/gogf/gf/v2/os/glog"
  7. )
  8. // ChatWs 聊天websocket请求
  9. var ChatWs = func(r *ghttp.Request) {
  10. session, _ := model.GetSession(r)
  11. model.SessionCtx.Init(r, &model.Context{
  12. JSession: session,
  13. })
  14. wsChat := model.NewMessage(r.Context())
  15. // 创建ws链接
  16. ws, err := r.WebSocket()
  17. if err != nil {
  18. glog.Error(wsChat.Ctx, session.AccountId, "建立连接出错", err)
  19. r.Exit()
  20. }
  21. if session.AccountId == 0 {
  22. _ = ws.WriteJSON(g.Map{
  23. "error_code": -1,
  24. "error_msg": "无用户身份",
  25. })
  26. return
  27. }
  28. for {
  29. // 接受客户端信息
  30. _, msg, err := ws.ReadMessage()
  31. if err != nil {
  32. glog.Info(wsChat.Ctx, session.AccountId, "接收消息出错", err)
  33. _ = ws.Close()
  34. return
  35. }
  36. rv := model.ChatLimit.GetBucket(wsChat.Ctx, session.AccountId).TakeAvailable(1)
  37. g.Log().Info(wsChat.Ctx, "c----", rv)
  38. if rv == 0 {
  39. g.Log().Info(wsChat.Ctx, "请求频繁")
  40. _ = ws.WriteJSON(g.Map{"error_code": 0, "error_msg": g.Cfg().MustGet(wsChat.Ctx, "limit.exceedMsg").String()})
  41. return
  42. }
  43. // 处理ws
  44. wsChat.Handle(ws, msg)
  45. }
  46. }