chatWs.go 916 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package controller
  2. import (
  3. "aiChat/internal/model"
  4. "aiChat/utility"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/net/ghttp"
  7. "github.com/gogf/gf/v2/os/gctx"
  8. "github.com/gogf/gf/v2/os/glog"
  9. )
  10. // ChatWs 聊天websocket请求
  11. var ChatWs = func(r *ghttp.Request) {
  12. session, _ := utility.GetSession(r)
  13. wsChat := model.NewMessage(gctx.New(), session.AccountId)
  14. // 创建ws链接
  15. ws, err := r.WebSocket()
  16. if err != nil {
  17. glog.Error(wsChat.Ctx, session.AccountId, "建立连接出错", err)
  18. r.Exit()
  19. }
  20. if session.AccountId == 0 {
  21. _ = ws.WriteJSON(g.Map{
  22. "error_code": -1,
  23. "error_msg": "无用户身份",
  24. })
  25. return
  26. }
  27. for {
  28. // 接受客户端信息
  29. _, msg, err := ws.ReadMessage()
  30. if err != nil {
  31. glog.Info(wsChat.Ctx, session.AccountId, "接收消息出错", err)
  32. _ = ws.Close()
  33. return
  34. }
  35. // 处理ws
  36. wsChat.Handle(ws, msg, r.GetClientIp(), r.UserAgent())
  37. }
  38. }