|
|
|
|
package protocol
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"git.noahlan.cn/noahlan/nnet/core"
|
|
|
|
|
"git.noahlan.cn/noahlan/nnet/entity"
|
|
|
|
|
"git.noahlan.cn/noahlan/nnet/middleware"
|
|
|
|
|
"git.noahlan.cn/noahlan/nnet/packet"
|
|
|
|
|
"git.noahlan.cn/noahlan/ntools-go/core/nlog"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type (
|
|
|
|
|
NNetConfig struct {
|
|
|
|
|
HeartbeatInterval time.Duration
|
|
|
|
|
HandshakeValidator HandshakeValidatorFunc
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
HandshakeReq struct {
|
|
|
|
|
Version string `json:"version"` // 客户端版本,服务器以此判断是否合适与客户端通信
|
|
|
|
|
Type string `json:"type"` // 客户端类型,与客户端版本号一起来确定客户端是否合适
|
|
|
|
|
ClientId string `json:"clientId"` // 客户端ID,服务器以此取值
|
|
|
|
|
ClientSecret string `json:"clientSecret"` // 客户端密钥,服务器以此判定客户端是否可用
|
|
|
|
|
|
|
|
|
|
// 透传信息
|
|
|
|
|
Payload interface{} `json:"payload,optional,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
HandshakeResp struct {
|
|
|
|
|
// 心跳间隔,单位秒 0表示不需要心跳
|
|
|
|
|
Heartbeat int64 `json:"heartbeat"`
|
|
|
|
|
|
|
|
|
|
*RouteMap
|
|
|
|
|
|
|
|
|
|
// 透传信息
|
|
|
|
|
Payload interface{} `json:"payload,optional,omitempty"`
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func WithNNetClientProtocol(onReady OnReadyFunc) []core.RunOption {
|
|
|
|
|
router := NewNNetRouter().(*nNetRouter)
|
|
|
|
|
packer := NewNNetPacker(router.routeMap)
|
|
|
|
|
opts := []core.RunOption{
|
|
|
|
|
WithNNetClientPipeline(onReady, packer),
|
|
|
|
|
core.WithRouter(router),
|
|
|
|
|
core.WithPacker(func() packet.Packer { return NewNNetPacker(router.routeMap) }),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return opts
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WithNNetProtocol(config NNetConfig) []core.RunOption {
|
|
|
|
|
if config.HandshakeValidator == nil {
|
|
|
|
|
config.HandshakeValidator = func(data *HandshakeReq) error {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
router := NewNNetRouter().(*nNetRouter)
|
|
|
|
|
handshakeAckData := &HandshakeResp{
|
|
|
|
|
Heartbeat: int64(config.HeartbeatInterval.Seconds()),
|
|
|
|
|
RouteMap: router.routeMap,
|
|
|
|
|
}
|
|
|
|
|
router.routeMap.Routes["hahah"] = 222
|
|
|
|
|
|
|
|
|
|
packer := NewNNetPacker(router.routeMap)
|
|
|
|
|
|
|
|
|
|
opts := []core.RunOption{
|
|
|
|
|
WithNNetPipeline(handshakeAckData, config.HandshakeValidator, packer),
|
|
|
|
|
core.WithRouter(router),
|
|
|
|
|
core.WithPacker(func() packet.Packer { return NewNNetPacker(router.routeMap) }),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if config.HeartbeatInterval.Seconds() > 0 {
|
|
|
|
|
hbd, err := packer.Pack(Heartbeat, nil)
|
|
|
|
|
nlog.Must(err)
|
|
|
|
|
|
|
|
|
|
opts = append(opts, middleware.WithHeartbeat(config.HeartbeatInterval, func(_ entity.NetworkEntity) []byte {
|
|
|
|
|
return hbd
|
|
|
|
|
}))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return opts
|
|
|
|
|
}
|