topfreegames / pitaya

Scalable game server framework with clustering support and client libraries for iOS, Android, Unity and others through the C SDK.
MIT License
2.38k stars 480 forks source link

anywhere, i can do something before shakehand? #386

Closed lazycatNewton closed 5 months ago

lazycatNewton commented 9 months ago

As a new pitaya user.

if i want do some validation work before shakehand, in session, what should i do ?

lazycatNewton commented 9 months ago

temporary solution:

i want set a function variable in App struct.

before pitaya-app started ,state it. im not sure this is correct (i did it in version 1.x). Maybe i can do something in SessionPool ? i still haven't quite figured out how it works.

thanks for your reply!

felipejfc commented 9 months ago

what is the use case you're trying to cover?

lazycatNewton commented 9 months ago

use case in demo (in pitaya version 1.x) :

func main() {
    defer pitaya.Shutdown()

    s := json.NewSerializer()
    conf := configApp()

    pitaya.SetSerializer(s)
    gsi := groups.NewMemoryGroupService(config.NewConfig(conf))
    pitaya.InitGroups(gsi)
    err := pitaya.GroupCreate(context.Background(), "room")
    if err != nil {
        panic(err)
    }

    // rewrite component and handler name
    room := NewRoom()
    pitaya.Register(room,
        component.WithName("room"),
        component.WithNameFunc(strings.ToLower),
    )

    log.SetFlags(log.LstdFlags | log.Llongfile)

    http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("web"))))

    go http.ListenAndServe(":3251", nil)

    t := acceptor.NewWSAcceptor(":3250")
    pitaya.AddAcceptor(t)
    pitaya.SetBeforeHandshake(func(s *session.Session, data *session.HandshakeData) error {

        t, ok := data.User["token"]
        if !ok {
            return fmt.Errorf("token not exist")
        }
        token, ok := t.(string)
        if !ok {
            return fmt.Errorf("token error")
        }

        logger.Log.Debugf("token ok %v", token)

        return nil
    })
    pitaya.Configure(true, "chat", pitaya.Standalone, map[string]string{}, conf)
    pitaya.Start()
type App struct {
// ...
    beforeHandshake  func(*session.Session, *session.HandshakeData) error
}
func SetBeforeHandshake(fn func(*session.Session, *session.HandshakeData) error) {
    app.beforeHandshake = fn
}

I'm not sure this is expected in pitaya. but it worked

What should I do better in pitaya-2.x?

thanks for the help !

f2ngwx commented 7 months ago

Change here

switch p.Type {
    case packet.Handshake:
        logger.Log.Debug("Received handshake packet")
        if err := a.SendHandshakeResponse(); err != nil {
            logger.Log.Errorf("Error sending handshake response: %s", err.Error())
            return err
        }
        logger.Log.Debugf("Session handshake Id=%d, Remote=%s", a.GetSession().ID(), a.RemoteAddr())

        // Parse the json sent with the handshake by the client
        handshakeData := &session.HandshakeData{}
        err := json.Unmarshal(p.Data, handshakeData)
        if err != nil {
            a.SetStatus(constants.StatusClosed)
            return fmt.Errorf("invalid handshake data. Id=%d", a.GetSession().ID())
        }

        a.GetSession().SetHandshakeData(handshakeData)
        a.SetStatus(constants.StatusHandshake)
        err = a.GetSession().Set(constants.IPVersionKey, a.IPVersion())
        if err != nil {
            logger.Log.Warnf("failed to save ip version on session: %q\n", err)
        }

        logger.Log.Debug("Successfully saved handshake data")
}
lazycatNewton commented 5 months ago

Change here

switch p.Type {
  case packet.Handshake:
      logger.Log.Debug("Received handshake packet")
      if err := a.SendHandshakeResponse(); err != nil {
          logger.Log.Errorf("Error sending handshake response: %s", err.Error())
          return err
      }
      logger.Log.Debugf("Session handshake Id=%d, Remote=%s", a.GetSession().ID(), a.RemoteAddr())

      // Parse the json sent with the handshake by the client
      handshakeData := &session.HandshakeData{}
      err := json.Unmarshal(p.Data, handshakeData)
      if err != nil {
          a.SetStatus(constants.StatusClosed)
          return fmt.Errorf("invalid handshake data. Id=%d", a.GetSession().ID())
      }

      a.GetSession().SetHandshakeData(handshakeData)
      a.SetStatus(constants.StatusHandshake)
      err = a.GetSession().Set(constants.IPVersionKey, a.IPVersion())
      if err != nil {
          logger.Log.Warnf("failed to save ip version on session: %q\n", err)
      }

      logger.Log.Debug("Successfully saved handshake data")
}

Thanks, for your answer. issue closed