wsLogic.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package user
  2. import (
  3. "context"
  4. "github.com/gorilla/websocket"
  5. "microGame/app/usercenter/cmd/api/internal/game"
  6. "net/http"
  7. "github.com/zeromicro/go-zero/core/logx"
  8. "microGame/app/usercenter/cmd/api/internal/svc"
  9. )
  10. var upgrade = websocket.Upgrader{
  11. ReadBufferSize: 1024,
  12. WriteBufferSize: 1024,
  13. CheckOrigin: func(r *http.Request) bool {
  14. return true
  15. },
  16. }
  17. type WsLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. // NewWsLogic ws
  23. func NewWsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WsLogic {
  24. return &WsLogic{
  25. Logger: logx.WithContext(ctx),
  26. ctx: ctx,
  27. svcCtx: svcCtx,
  28. }
  29. }
  30. // Ws 程序退出关闭所有长连接
  31. func (l *WsLogic) Ws(w http.ResponseWriter, r *http.Request) {
  32. k := r.URL.Query().Get("k")
  33. if k == "" {
  34. return
  35. }
  36. conn, err := upgrade.Upgrade(w, r, nil)
  37. if err != nil {
  38. return
  39. }
  40. client := &game.Player{
  41. SvcCtx: l.svcCtx,
  42. Conn: conn,
  43. Send: make(chan []byte, game.BufSize),
  44. //Uid: 100,
  45. }
  46. client.SvcCtx.Hub.Register <- client
  47. go client.WritePump()
  48. go client.ReadPump()
  49. }