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.
nnet/protocol/nnet.go

87 lines
2.2 KiB
Go

2 years ago
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"
)
2 years ago
type (
NNetConfig struct {
HeartbeatInterval time.Duration
HandshakeValidator HandshakeValidatorFunc
2 years ago
}
HandshakeReq struct {
2 years ago
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 {
2 years ago
// 心跳间隔,单位秒 0表示不需要心跳
Heartbeat int64 `json:"heartbeat"`
2 years ago
*RouteMap
2 years ago
// 透传信息
Payload interface{} `json:"payload,optional,omitempty"`
2 years ago
}
2 years ago
)
2 years ago
var routeMap *RouteMap
func init() {
routeMap = &RouteMap{
Routes: make(map[string]uint16),
Codes: make(map[uint16]string),
}
}
func WithNNetClientProtocol(onReady OnReadyFunc) []core.RunOption {
opts := []core.RunOption{
WithNNetClientPipeline(onReady),
core.WithRouter(NewNNetRouter()),
core.WithPacker(func() packet.Packer { return NewNNetPacker() }),
}
return opts
}
2 years ago
func WithNNetProtocol(config NNetConfig) []core.RunOption {
if config.HandshakeValidator == nil {
config.HandshakeValidator = func(data *HandshakeReq) error {
return nil
2 years ago
}
}
handshakeAckData := &HandshakeResp{
Heartbeat: int64(config.HeartbeatInterval.Seconds()),
RouteMap: routeMap,
}
2 years ago
opts := []core.RunOption{
WithNNetPipeline(handshakeAckData, config.HandshakeValidator),
2 years ago
core.WithRouter(NewNNetRouter()),
core.WithPacker(func() packet.Packer { return NewNNetPacker() }),
2 years ago
}
if config.HeartbeatInterval.Seconds() > 0 {
packer := NewNNetPacker()
hbd, err := packer.Pack(Heartbeat, nil)
2 years ago
nlog.Must(err)
opts = append(opts, middleware.WithHeartbeat(config.HeartbeatInterval, func(_ entity.NetworkEntity) []byte {
2 years ago
return hbd
2 years ago
}))
2 years ago
}
2 years ago
return opts
2 years ago
}