package nnet import ( "encoding/json" "errors" "fmt" "git.noahlan.cn/noahlan/nnet" "git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/ntools-go/core/nlog" ) type OnReadyFunc func() func WithNNetClientPipeline(onReady OnReadyFunc, packer packet.Packer) nnet.RunOption { return func(ngin *nnet.Engine) { ngin.Pipeline().Inbound().PushFront(func(conn *connection.Connection, v interface{}) error { pkg, ok := v.(*Packet) if !ok { return packet.ErrWrongPacketType } nc, _ := conn.Conn() // Server to client switch pkg.PacketType { case Handshake: var handshakeData HandshakeResp err := json.Unmarshal(pkg.Data, &handshakeData) nlog.Must(err) hrd, _ := packer.Pack(Header{ PacketType: HandshakeAck, MessageHeader: MessageHeader{}, }, nil) if err := conn.SendBytes(hrd); err != nil { return err } conn.SetStatus(connection.StatusWorking) // onReady if onReady != nil { onReady() } nlog.Debugf("connection handshake Id=%d, Remote=%s", conn.Session().ID(), nc.RemoteAddr()) case Kick: _ = conn.Close() case Data: status := conn.Status() if status != connection.StatusWorking { return errors.New(fmt.Sprintf("receive data on socket which not yet ACK, session will be closed immediately, remote=%s", nc.RemoteAddr())) } var lastMid uint64 switch pkg.MsgType { case Response: lastMid = pkg.ID case Notify: lastMid = 0 } conn.SetLastMID(lastMid) } return nil }) } }