add clinettest

This commit is contained in:
sk 2025-01-09 09:15:40 +08:00
parent 0f3508b2f8
commit 1e0572c537
8 changed files with 450 additions and 0 deletions

105
clienttest/action_login.go Normal file
View File

@ -0,0 +1,105 @@
package main
import (
"encoding/json"
"fmt"
"math/rand"
"mongo.games.com/game/protocol/activity"
"mongo.games.com/goserver/core/timer"
"time"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
"mongo.games.com/game/model"
"mongo.games.com/game/proto"
loginproto "mongo.games.com/game/protocol/login"
playerproto "mongo.games.com/game/protocol/player"
)
func init() {
// 心跳
netlib.Register(int(loginproto.GatePacketID_PACKET_SC_PONG), loginproto.SCPong{}, SCPong)
// 登录
netlib.Register(int(loginproto.LoginPacketID_PACKET_SC_LOGIN), loginproto.SCLogin{}, SCLogin)
// 玩家信息
netlib.Register(int(playerproto.PlayerPacketID_PACKET_SC_PLAYERDATA), playerproto.SCPlayerData{}, SCPlayerData)
netlib.Register(int(activity.PushCoinPacketID_PACKET_SCPushCoinInfo), activity.SCPushCoinInfo{}, SCPrint)
}
func SCPong(s *netlib.Session, packetid int, data interface{}) error {
accountID := s.GetAttribute(SessionAttributeClientAccountId)
logger.Logger.Tracef("SCPong username:%v %v", accountID, data)
return nil
}
func SCLogin(s *netlib.Session, packetid int, data interface{}) error {
logger.Logger.Trace("SCLogin ", data)
msg, ok := data.(*loginproto.SCLogin)
if !ok {
return nil
}
if msg.GetOpRetCode() != loginproto.OpResultCode_OPRC_Sucess {
accountID := s.GetAttribute(SessionAttributeClientAccountId)
logger.Logger.Error("登录失败 ", accountID)
s.Close()
return nil
}
csPlayerData := &playerproto.CSPlayerData{
AccId: msg.GetAccId(),
}
pp := &model.PlayerParams{
Platform: 1,
Ip: fmt.Sprintf("%v.%v.%v.%v", 1+rand.Int31n(255), 1+rand.Int31n(255), 1+rand.Int31n(255), 1+rand.Int31n(255)),
City: "北京",
Logininmodel: "app",
}
d, err := json.Marshal(pp)
if err == nil {
csPlayerData.Params = proto.String(string(d))
}
s.Send(int(playerproto.PlayerPacketID_PACKET_CS_PLAYERDATA), csPlayerData)
logger.Logger.Info("登录成功 ", msg.GetAccId())
return nil
}
func SCPlayerData(s *netlib.Session, packetid int, data interface{}) error {
logger.Logger.Trace("SCPlayerData ", data)
msg, ok := data.(*playerproto.SCPlayerData)
if !ok {
return nil
}
if msg.GetOpRetCode() != playerproto.OpResultCode_OPRC_Sucess {
accountID := s.GetAttribute(SessionAttributeClientAccountId)
logger.Logger.Errorf("获取玩家信息失败 %v", accountID)
s.Close()
return nil
}
s.SetAttribute(SessionAttributeUser, msg)
StartSessionPingTimer(s, timer.TimerActionWrapper(func(h timer.TimerHandle, ud interface{}) bool {
if !s.IsConned() {
StopSessionPingTimer(s)
return false
}
pack := &loginproto.CSPing{}
s.Send(int(loginproto.GatePacketID_PACKET_CS_PING), pack)
return true
}), nil, time.Second*time.Duration(60+rand.Int31n(100)), -1)
s.Send(int(activity.PushCoinPacketID_PACKET_CSPushCoinInfo), &activity.CSPushCoinInfo{})
return nil
}
func SCPrint(s *netlib.Session, packetid int, data interface{}) error {
logger.Logger.Info("SCPrint ", data)
return nil
}

35
clienttest/config.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"mongo.games.com/goserver/core"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
)
var Config = &Configuration{}
type Configuration struct {
Count int // 机器人总数
AppId string // appID
Connects netlib.SessionConfig // 网络连接配置
}
func (this *Configuration) Name() string {
return "benchmark"
}
func (this *Configuration) Init() error {
logger.Logger.Tracef("%+v", *this)
if this.Count == 0 {
this.Count = 20
}
return nil
}
func (this *Configuration) Close() error {
return nil
}
func init() {
core.RegistePackage(Config)
}

67
clienttest/config.yaml Normal file
View File

@ -0,0 +1,67 @@
netlib:
SrvInfo:
Name: BenchmarkServer
Type: 9
Id: 902
AreaID: 1
Banner:
- =================
- benchmark server
- =================
IoServices: []
module:
Options:
QueueBacklog: 1024
MaxDone: 1024
Interval: 100
executor:
Options:
QueueBacklog: 1024
MaxDone: 1024
Interval: 0
Worker:
WorkerCnt: 8
Options:
QueueBacklog: 1024
MaxDone: 1024
Interval: 0
timer:
Options:
QueueBacklog: 1024
MaxDone: 1024
Interval: 100
signal:
SupportSignal: true
cmdline:
SupportCmdline: true
benchmark:
Count: 1
AppId: 5c56d1644966f078bfb90c71
Connects:
Id: 402
Type: 4
AreaId: 1
Name: ClientService
Ip: 127.0.0.1
Port: 11001
Protocol: tcp
Path: /
MaxDone: 200
MaxPend: 200
MaxPacket: 65535
MaxConn: 2000
RcvBuff: 4096
SndBuff: 4096
WriteTimeout: 3600
ReadTimeout: 3600
SoLinger: 10
IsInnerLink: true
NoDelay: true
SupportFragment: true
AuthKey: www.jxjy.games.cn
IsClient: true
AllowMultiConn: true
FilterChain:
- session-filter-auth
HandlerChain:
- handler-gate-session

69
clienttest/connect.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"time"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/module"
"mongo.games.com/goserver/core/netlib"
)
const (
// RobotSessionStartId 机器人session开始id
RobotSessionStartId = 100000000
)
var (
BenchMarkModule = &BenchMark{}
WaitConnectSessions []*netlib.SessionConfig
)
// NewSession 新建session
// id 连接id, 默认自动分配
func NewSession(id ...int) {
cfg := Config.Connects
if len(id) > 0 && id[0] > 0 {
cfg.Id = id[0]
} else {
BenchMarkModule.idx++
cfg.Id = BenchMarkModule.idx
}
cfg.Init()
logger.Logger.Info("waite connect session id=", cfg.Id)
WaitConnectSessions = append(WaitConnectSessions, &cfg)
}
type BenchMark struct {
idx int
}
func (m *BenchMark) ModuleName() string {
return "benchmark-module"
}
func (m *BenchMark) Init() {
m.idx = RobotSessionStartId
for i := 0; i < Config.Count; i++ {
NewSession()
}
}
// Update 机器开始连接游戏服务器
func (m *BenchMark) Update() {
n := len(WaitConnectSessions)
if n > 0 {
config := WaitConnectSessions[n-1]
WaitConnectSessions = WaitConnectSessions[:n-1]
if err := netlib.Connect(config); err != nil {
logger.Logger.Error("netlib.Connect error", err)
}
}
}
func (m *BenchMark) Shutdown() {
module.UnregisteModule(m)
}
func init() {
module.RegisteModule(BenchMarkModule, time.Millisecond, 1)
}

31
clienttest/constants.go Normal file
View File

@ -0,0 +1,31 @@
package main
import (
"mongo.games.com/goserver/core/netlib"
"mongo.games.com/goserver/core/timer"
"time"
)
const (
SessionAttributeClientAccountId int = iota // 账号
SessionAttributeUser
SessionAttributePingTimer
)
func StartSessionPingTimer(s *netlib.Session, act timer.TimerAction, ud interface{}, interval time.Duration, times int) bool {
StopSessionPingTimer(s)
if hTimer, ok := timer.StartTimer(act, ud, interval, times); ok {
s.SetAttribute(SessionAttributePingTimer, hTimer)
return true
}
return false
}
func StopSessionPingTimer(s *netlib.Session) {
if h, ok := s.GetAttribute(SessionAttributePingTimer).(timer.TimerHandle); ok {
if h != timer.TimerHandle(0) {
timer.StopTimer(h)
s.RemoveAttribute(SessionAttributePingTimer)
}
}
}

View File

@ -0,0 +1,97 @@
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"mongo.games.com/game/common"
"mongo.games.com/game/model"
loginproto "mongo.games.com/game/protocol/login"
"mongo.games.com/goserver/core/logger"
"mongo.games.com/goserver/core/netlib"
"strconv"
"sync/atomic"
"time"
)
/*
添加到客户端管理器管理器负责登录
当连接断开时从管理器中移除判断是否需要重连
*/
const (
GateSessionHandlerName = "handler-gate-session"
)
type GateSessionHandler struct {
netlib.BasicSessionHandler
}
func (g *GateSessionHandler) GetName() string {
return GateSessionHandlerName
}
func (g *GateSessionHandler) GetInterestOps() uint {
return 1<<netlib.InterestOps_Opened |
1<<netlib.InterestOps_Closed
}
func (g *GateSessionHandler) OnSessionOpened(s *netlib.Session) {
// 登录账号
StartLogin(s)
return
}
func (g *GateSessionHandler) OnSessionClosed(s *netlib.Session) {
}
func init() {
netlib.RegisteSessionHandlerCreator(GateSessionHandlerName, func() netlib.SessionHandler {
return &GateSessionHandler{}
})
}
var UserNameIndex int64
func StartLogin(s *netlib.Session) {
ts := time.Now().UnixNano()
username := fmt.Sprintf("benchmark-%v", atomic.AddInt64(&UserNameIndex, 1))
s.SetAttribute(SessionAttributeClientAccountId, username)
csLogin := &loginproto.CSLogin{
Username: username,
TimeStamp: ts,
Platform: "1",
Channel: "",
PlatformTag: "test.win88.yy_android",
}
params := &model.PlayerParams{
Ip: fmt.Sprintf("%v.%v.%v.%v", 1+rand.Int31n(255), 1+rand.Int31n(255), 1+rand.Int31n(255), 1+rand.Int31n(255)),
City: "北京",
Platform: 1,
Logininmodel: "app",
}
data, err := json.Marshal(params)
if err == nil {
csLogin.Params = string(data[:])
}
h := md5.New()
io.WriteString(h, fmt.Sprintf("%v%v", username, Config.AppId))
pwd := hex.EncodeToString(h.Sum(nil))
h.Reset()
io.WriteString(h, fmt.Sprintf("%v%v%v", pwd, Config.AppId, ts))
pwd = hex.EncodeToString(h.Sum(nil))
csLogin.Password = pwd
csLogin.LoginType = 0
csLogin.Sign = common.MakeMd5String(csLogin.GetUsername(), csLogin.GetPassword(),
strconv.Itoa(int(csLogin.GetTimeStamp())), csLogin.GetParams(), Config.AppId)
s.Send(int(loginproto.LoginPacketID_PACKET_CS_LOGIN), csLogin)
logger.Logger.Infof("账号 [%v] 开始登录", username)
}

22
clienttest/logger.xml Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8" ?>
<seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="trace">
<exceptions>
<exception filepattern="test*" minlevel="error"/>
</exceptions>
<outputs formatid="all">
<rollingfile formatid="all" type="size" filename="./all.log" maxsize="50000000" maxrolls="5" />
<filter levels="info,trace,warn,error">
<console formatid="fmtinfo"/>
</filter>
<filter levels="error,critical" formatid="fmterror">
<console/>
<file path="errors.log"/>
</filter>
</outputs>
<formats>
<format id="fmtinfo" format="[%Date][%Time] [%Level] %Msg%n"/>
<format id="fmterror" format="[%Date][%Time] [%LEVEL] [%FuncShort @ %File.%Line] %Msg%n"/>
<format id="all" format="[%Date][%Time] [%Level] [@ %File.%Line] %Msg%n"/>
<format id="criticalemail" format="Critical error on our server!\n %Time %Date %RelFile %Func %Msg \nSent by Seelog"/>
</formats>
</seelog>

24
clienttest/main.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
_ "mongo.games.com/game"
"mongo.games.com/goserver/core"
"mongo.games.com/goserver/core/module"
)
func main() {
defer core.ClosePackages()
core.LoadPackages("config.yaml")
// core hook
core.RegisteHook(core.HOOK_BEFORE_START, func() error {
return nil
})
core.RegisteHook(core.HOOK_AFTER_STOP, func() error {
return nil
})
// module模块
waiter := module.Start()
waiter.Wait("main()")
}