chatWs.go 912 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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/gctx"
  7. "github.com/gogf/gf/v2/os/glog"
  8. )
  9. // ChatWs 聊天websocket请求
  10. var ChatWs = func(r *ghttp.Request) {
  11. session, _ := model.GetSession(r)
  12. model.SessionCtx.Init(r, &model.Context{
  13. JSession: session,
  14. })
  15. wsChat := model.NewMessage(gctx.New())
  16. // 创建ws链接
  17. ws, err := r.WebSocket()
  18. if err != nil {
  19. glog.Error(wsChat.Ctx, session.AccountId, "建立连接出错", err)
  20. r.Exit()
  21. }
  22. if session.AccountId == 0 {
  23. _ = ws.WriteJSON(g.Map{
  24. "error_code": -1,
  25. "error_msg": "无用户身份",
  26. })
  27. return
  28. }
  29. for {
  30. // 接受客户端信息
  31. _, msg, err := ws.ReadMessage()
  32. if err != nil {
  33. glog.Info(wsChat.Ctx, session.AccountId, "接收消息出错", err)
  34. _ = ws.Close()
  35. return
  36. }
  37. // 处理ws
  38. wsChat.Handle(ws, msg)
  39. }
  40. }