You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package nnet
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"git.noahlan.cn/noahlan/nnet"
|
|
"git.noahlan.cn/noahlan/nnet/conn"
|
|
"git.noahlan.cn/noahlan/nnet/event"
|
|
"git.noahlan.cn/noahlan/nnet/packet"
|
|
"git.noahlan.cn/noahlan/ntool/nlog"
|
|
)
|
|
|
|
type OnReadyFunc func()
|
|
|
|
func WithNNetClientEvents(onReady OnReadyFunc, packer packet.Packer) nnet.RunOption {
|
|
return func(ngin *nnet.Engine) {
|
|
ngin.EventManager().RegisterEventFront(event.EvtOnReceive, onReceiveEvent(ngin, onReady, packer))
|
|
}
|
|
}
|
|
|
|
func onReceiveEvent(ngin *nnet.Engine, onReady OnReadyFunc, packer packet.Packer) event.OnReceiveFn {
|
|
return func(nc *conn.Connection, p packet.IPacket) {
|
|
pkg, ok := p.(*Packet)
|
|
if !ok {
|
|
nlog.Error(packet.ErrWrongPacketType)
|
|
return
|
|
}
|
|
// 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 := nc.SendBytes(hrd); err != nil {
|
|
return
|
|
}
|
|
nc.SetStatus(conn.StatusWorking)
|
|
// onReady
|
|
if onReady != nil {
|
|
onReady()
|
|
}
|
|
if ngin.ShallLogDebug() {
|
|
nlog.Debugf("connection handshake Id=%d, Remote=%s", nc.Session().ID(), nc.Conn().RemoteAddr())
|
|
}
|
|
case Kick:
|
|
_ = nc.Close()
|
|
case Data:
|
|
status := nc.Status()
|
|
if status != conn.StatusWorking {
|
|
nlog.Errorf(fmt.Sprintf("receive data on socket which not yet ACK, session will be closed immediately, remote=%s",
|
|
nc.Conn().RemoteAddr()))
|
|
return
|
|
}
|
|
|
|
var lastMid uint64
|
|
switch pkg.MsgType {
|
|
case Response:
|
|
lastMid = pkg.ID
|
|
case Notify:
|
|
lastMid = 0
|
|
}
|
|
nc.SetLastMID(lastMid)
|
|
}
|
|
}
|
|
}
|