You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1305 lines
50 KiB

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
namespace SogClient
{
public static class LoginCount
{
public static int Count = 0;
public static object lockcount = new object();
public static Dictionary<long, string> UidAccountIdMap = new Dictionary<long, string>();
}
public enum SessionType
{
None = 0,
AccountSession,
ChatSession,
GameSession,
Max,
}
public enum UseGateType
{
TCP = 0,
UDP,
WEBSOCKET,
Max,
}
public class Player
{
private string m_accountId;
private int m_accountType;
private string m_accountToken;
private int m_threadSerial;
private int m_playerCount;
public PlayerDataCache m_playerCache;
public PlayerState State = PlayerState.PlayerState_Init;
private bool IsConnectChat = false;
private bool IsLoginChat = false;
private long LoginToken = 0;
private ClientSession m_sessionAccount;
private ClientSession m_sessionGame;
private ClientSession m_sessionChat;
private WebClientSession m_webSessionAccount;
private WebClientSession m_webSessionGame;
private WebClientSession m_webSessionChat;
AccountInfo m_accountInfo = new AccountInfo();
VersionInfo m_versionInfo = new VersionInfo();
long m_uid;
long m_checkcode;
CSRealmInfo m_GameInfo;
private TestHandlerMgr m_testHandlerMgr;
//开始连接version的时间,统计一下登录总共花的时间
private DateTime m_startConnectTime;
private ConnectedClientSessionUpdate m_sessionUpdate;
private bool m_needReconnectAccount;
private long m_accountDisconnectTime;
private bool m_needReconnectGame;
private long m_gameDisconnectTime;
private long m_lastChatTime = 0;
private long m_lastSendtoGameTime = 0;
//已经断开连接了
private bool m_IsDisconnected = true;
// chat是否回复ping消息
private bool m_IsResChatPing = true;
// chatping 个数
private int m_chatPingCount = 0;
// game是否回复ping消息
private bool m_IsResGamePing = true;
// gameping个数
private int m_gamePingCount = 0;
//副本战斗要用
public ulong m_battleId = 0;
public bool m_isInCopy = false;
public string GetPlayerAccountId()
{
return m_accountId;
}
public Player(int accountType, string accountId, string accountToken, ConnectedClientSessionUpdate sessionUpdate, int playerCount, int threadSerial)
{
m_accountType = accountType;
m_accountId = accountId;
m_accountToken = accountToken;
m_sessionUpdate = sessionUpdate;
m_threadSerial = threadSerial;
m_playerCount = playerCount;
m_playerCache = new PlayerDataCache(this);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(Config.ClientTestConfig.serverIp), Config.ClientTestConfig.serverPort);
ClientSessionSettings clientSettings = new ClientSessionSettings(1024000, endPoint, Config.ClientTestConfig.cryptoMessage);
InitAccountSession(clientSettings);
m_testHandlerMgr = new TestHandlerMgr(this);
m_testHandlerMgr.RegisterAllPacketHandler();
}
/// <summary>
/// 构建netSession 的 sessionId
/// </summary>
/// <param name="sessionType">枚举值</param>
/// <param name="threadSerial"></param>
/// <param name="playerCount"></param>
/// <returns></returns>
public long CalculateSessionId(int sessionType, int threadSerial, int playerCount)
{
/*
* retSessionId note:
* -1 00 00000- 顺序从左到右
* 最高位 表示 Session 类型 accout:1, chat:2, server:3
* 2,3 位数字表示线程编号
* 4 5 6 7 8 剩余表示目前线程玩家编号
*/
long retSessionId = 10000000 * sessionType + threadSerial * 100000 + playerCount;
return retSessionId;
}
public void Start()
{
m_startConnectTime = DateTime.Now;
SessionConnect(SessionType.AccountSession);
//TraceLog.Debug("Player Start login : accountid {0} ", this.m_accountId);
}
public bool Update(long nowMs)
{
if (m_needReconnectAccount && nowMs >= m_accountDisconnectTime + 2000)
{
SessionReconnect(SessionType.AccountSession);
m_needReconnectAccount = false;
}
// 检测是否链接Accout
UpdateSession(SessionType.AccountSession, nowMs);
if (IsSessionConnected(SessionType.AccountSession) && State == PlayerState.PlayerState_Init)
{
// 发送登录消息
SendAccountAuthReq();
State = PlayerState.PlayerState_AccountLogin;
}
if (State >= PlayerState.PlayerState_ConnectingGame)
{
if (m_needReconnectGame && nowMs >= m_gameDisconnectTime + 5000)
{
SessionReconnect(SessionType.GameSession);
m_needReconnectGame = false;
}
// 游戏服务器链接初始化
UpdateSession(SessionType.GameSession, nowMs);
}
if(State == PlayerState.PlayerState_ConnectingGame)
{
// 已登录account,未链接游戏
if (IsSessionConnected(SessionType.GameSession))
{
State = PlayerState.PlayerState_LoginGame;
SendLoginToGameServer();
}
}
if(State == PlayerState.PlayerState_InGame)
{
// 已链接,已登录,游戏中
//if (m_sessionChat != null)
//{
// UpdateSession(SessionType.ChatSession, nowMs);
// if (IsSessionConnected(SessionType.ChatSession) && nowMs > m_lastChatTime + 10000)
// {
// if (IsLoginChat)
// {
// //SendChatToWorld("hero121212");
// //SendChatToTarget("大傻吊", 121212);
// }
// else
// {
// // 一登陆聊天服务器就会请求好友的聊天数据,造成好友服务器内存和cpu占用过高
// //SendLoginMsgToChat();
// }
// //SendFindRoleInfo();
// //SendRankDataReq();
// m_lastChatTime = nowMs;
// }
//}
if (IsSessionConnected(SessionType.GameSession) && nowMs > m_lastSendtoGameTime + 20000)
{
SendPingToGameServer();
}
//其他模块的测试消息发送
m_testHandlerMgr.UpdateAllHandler();
}
return true;
}
private void SendAccountAuthReq()
{
m_accountInfo.AccountType = m_accountType;
m_accountInfo.AccountID = m_accountId;
m_accountInfo.AccountToken = m_accountToken;
CSAccountAuthReq accountReq = new CSAccountAuthReq();
accountReq.Account = m_accountInfo;
accountReq.Channel = "comm";
accountReq.DeviceId = "deviceid_windows_test";
accountReq.DeviceInfo = "windows";
accountReq.OsInfo = "windows";
m_versionInfo.AppVersion = "0.1.2";
m_versionInfo.Language = "en";
m_versionInfo.Os = "win";
accountReq.Version = m_versionInfo;
accountReq.Timezone = 8;
accountReq.NetInfo = "local";
//TraceLog.Debug("SendAccountAuthReq SendMsgToAccount : {0} SessionID:{1}", accountReq.Account.AccountID, GetSessionIDBySessionType(SessionType.AccountSession));
TraceLog.Debug("发起账号登录: {0}", accountReq.Account.AccountID);
SendMsgToAccount(accountReq, (int)CSMsgID.AccountReq, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.AccountSession)));
}
private void SendMsgToAccount(IMessage pbMessage,int iMsgID,uint iSessionID)
{
RequestPacket packet = new RequestPacket(iMsgID, 0, iSessionID);
packet.Packet = pbMessage;
MessageData message;
message.Header.Type = iMsgID;
message.Header.Length = 0;
message.Header.ObjectID = 0;
message.Header.ServerID = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.AccountSession);
//TraceLog.Debug("SendMsgToAccount over SessionID: {0}", GetSessionIDBySessionType(SessionType.AccountSession));
}
public void SendMsgToGame(IMessage pbMessage, int iMsgID, uint iSessionID)
{
RequestPacket packet = new RequestPacket(iMsgID, 0, iSessionID);
packet.Packet = pbMessage;
MessageData message;
message.Header.Type = iMsgID;
message.Header.Length = 0;
message.Header.ObjectID = 0;
message.Header.ServerID = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.GameSession);
}
public void SendMsgToChat(IMessage pbMessage, int iMsgID, uint iSessionID)
{
RequestPacket packet = new RequestPacket(iMsgID, 0, iSessionID);
packet.Packet = pbMessage;
MessageData message;
message.Header.Type = iMsgID;
message.Header.Length = 0;
message.Header.ObjectID = 0;
message.Header.ServerID = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.ChatSession);
}
public void SendMsgToChat(string msg, ChatChannelType type)
{
CSChatReq req = new CSChatReq();
req.Uid = m_uid;
req.ChatChannelType = type;
req.CheckToken = LoginToken;
req.Message = msg;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.ChatReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.ChatReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("SendMsgToChat PackMessage error");
return;
}
SendMessageToSession(message, SessionType.ChatSession);
}
public void SendChatToWorld(string msg)
{
CSChatReq req = new CSChatReq();
req.Uid = m_uid;
req.ChatChannelType = ChatChannelType.World;
req.CheckToken = LoginToken;
req.Message = msg;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.ChatReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.ChatReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("SendChatToWorld PackMessage error");
return;
}
SendMessageToSession(message, SessionType.ChatSession);
TraceLog.Debug("SendChatToWorld :" + msg );
}
public void SendChatToTarget(string msg, long targetUid)
{
CSChatReq req = new CSChatReq();
req.Uid = m_uid;
req.TargetUid = targetUid;
req.ChatChannelType = ChatChannelType.Friend;
req.CheckToken = LoginToken;
req.Message = msg;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.ChatReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.ChatReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("SendChatToTarget PackMessage error");
return;
}
SendMessageToSession(message, SessionType.ChatSession);
TraceLog.Debug("SendChatToTarget msg:{1} uid:{2}", msg, targetUid);
}
public void SendLoginMsgToChat()
{
CSChatLoginReq req = new CSChatLoginReq();
req.PlayerUid = m_uid;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.ChatloginReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.ChatloginReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.ChatSession);
}
public void SendFindRoleInfo()
{
CSPlayerQueryOtherRoleInfoReq req = new CSPlayerQueryOtherRoleInfoReq();
req.TargetUid = 100003;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.PlayerQueryOtherRoleInfoReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.ChatloginReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.GameSession);
}
public void SendRankDataReq()
{
CSQueryRankListReq req = new CSQueryRankListReq();
req.RankId = 4000;
req.StartPos = 1;
req.EndPos = 50;
RequestPacket packet = new RequestPacket((int)CSGameMsgID.QueryRankListReq, 0, 0);
packet.Packet = req;
MessageData message = new MessageData();
message.Header.Type = (int)CSGameMsgID.QueryRankListReq;
message.Header.Length = 0;
message.Data = null;
bool bRet = ProtoPackerFactory.Instance.GetProtoPacker().PackMessage(packet, ref message);
if (bRet == false)
{
TraceLog.Error("PackMessage error");
return;
}
SendMessageToSession(message, SessionType.GameSession);
}
void OnWebAccDisconnected(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
TraceLog.Trace("------ OnWebAccDisconnected -----");
AccDisconnected();
}
void OnAccDisconnected(IMessageTrans messageTrans, SessionEventArgs e)
{
TraceLog.Trace("------ OnAccDisconnected -----");
AccDisconnected();
}
void AccDisconnected()
{
//没拉取到游戏列表,需要重连
if (m_GameInfo == null)
{
m_needReconnectAccount = true;
m_accountDisconnectTime = TimeUtils.GetTime();
this.State = PlayerState.PlayerState_Init;
}
else
{
ReleaseAccountSession();
}
}
void OnWebAccountMsgRecied(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
MessageData message = e.Message;
AccountMsgReceived(message);
}
void OnAccountMsgReceived(IMessageTrans messageTrans, SessionEventArgs e)
{
MessageData message = e.Message;
AccountMsgReceived(message);
}
void AccountMsgReceived(MessageData message)
{
RequestPacket packet;
bool result = ProtoPackerFactory.Instance.GetProtoPacker().UnpackMessage(message, out packet);
if (result)
{
// log message
Google.Protobuf.IMessage pbMessage = (Google.Protobuf.IMessage)(packet.Packet);
//TraceLog.Debug("OnAccountMsgReceived recv message from server, message type {0} MsgID {1} length {2} : {3}"
// , message.Header.Type
// , packet.MsgID
// , message.Header.Length
// , pbMessage.ToString()
// );
if (packet.MsgID == (int)CSMsgID.AccountRes)
{
CSAccountAuthRes accountAuthRes = (CSAccountAuthRes)packet.Packet;
if (accountAuthRes.Ret == 0)
{
m_checkcode = accountAuthRes.CheckCode;
TraceLog.Debug("账号登录成功: {0}", accountAuthRes.Account.AccountID);
SendQueryGameListReq();
State = PlayerState.PlayerState_GetGameList;
}
else
{
TraceLog.Debug("账号登录失败原因:{0}", accountAuthRes.Ret);
}
}
else if (packet.MsgID == (int)CSMsgID.GameListRes)
{
CSGameListRes gameListRes = (CSGameListRes)packet.Packet;
if (gameListRes.Realms.Count > 0)
{
//int realmNum = m_playerCount % gameListRes.Realms.Count;
m_GameInfo = gameListRes.Realms[0];
//TraceLog.Debug("OnAccountMsgReceived get game info name {0} online {1} url {2} port {3}",
// m_GameInfo.Name, m_GameInfo.OnlinePlayer, m_GameInfo.GateUrl, m_GameInfo.GateUrl);
TraceLog.Debug("拉取区服列表成功 有数量:{0} 大区名 {1} ip端口 {2}",m_accountId, m_GameInfo.Name,m_GameInfo.GateUrl);
StartConnectGame();
State = PlayerState.PlayerState_ConnectingGame;
}
else
{
m_GameInfo = gameListRes.RecommendRealm;
TraceLog.Debug("拉取推荐区服成功 推荐服:{0} 大区名 {1} ip端口 {2}", m_accountId, m_GameInfo.Name, m_GameInfo.GateUrl);
StartConnectGame();
State = PlayerState.PlayerState_ConnectingGame;
}
}
else
{
TraceLog.Error("OnAccountMsgReceived recv message from server, message no support!");
}
}
else
{
//TODO 暂时屏蔽了
//TraceLog.Error("OnAccountMsgReceived recv message from server, message UnpackMessage Filed!");
}
}
void OnWebAccountConnectFail(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
AccountConnectFail();
}
void OnAccountConnectFail(IMessageTrans messageTrans, SessionEventArgs e)
{
AccountConnectFail();
}
void AccountConnectFail()
{
m_needReconnectAccount = true;
m_accountDisconnectTime = TimeUtils.GetTime();
}
void OnWebGameDisconnected(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
TraceLog.Debug("------ OnWebGameDisconnected -----");
GameDisconnected();
}
void OnGameDisconnected(IMessageTrans messageTrans, SessionEventArgs e)
{
TraceLog.Debug("------ OnGameDisconnected -----");
GameDisconnected();
}
void GameDisconnected()
{
m_needReconnectGame = true;
m_gameDisconnectTime = TimeUtils.GetTime();
State = PlayerState.PlayerState_ConnectingGame;
}
void OnWebGameConnectFail(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
GameConnectFail();
}
void OnGameConnectFail(IMessageTrans messageTrans, SessionEventArgs e)
{
GameConnectFail();
}
void GameConnectFail()
{
m_needReconnectGame = true;
m_gameDisconnectTime = TimeUtils.GetTime();
}
private void SendQueryGameListReq()
{
CSGameListReq gameListReq = new CSGameListReq();
SendMsgToAccount(gameListReq, (int)CSMsgID.GameListReq, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.AccountSession)));
TraceLog.Debug("请求区服列表: {0}", m_accountId);
}
private void StartConnectGame()
{
string[] ipport = m_GameInfo.GateUrl.Split(":");
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipport[0]), int.Parse(ipport[1]));
//TraceLog.Debug("StartConnectGame connect to {0} {1}" , ipport[0], ipport[1]);
int bufferSize = 1024000;
ClientSessionSettings clientSettings = new ClientSessionSettings(bufferSize, endPoint,
Config.ClientTestConfig.cryptoMessage);
InitGameSession(clientSettings);
SessionConnect(SessionType.GameSession);
}
private void StartConnectChat()
{
string[] ipport = m_GameInfo.ChatGateUrl.Split(':');
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipport[0]), int.Parse(ipport[1]));
//TraceLog.Debug("StartConnectChat uid:{0} , ipport :{1}", m_uid, ipport);
//string ip = "192.168.1.199";
//string port = "9810";
//IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
ClientSessionSettings clientSettings = new ClientSessionSettings(1024000, endPoint, Config.ClientTestConfig.cryptoMessage);
InitChatSession(clientSettings);
SessionConnect(SessionType.ChatSession);
}
void OnChatDisconnected(IMessageTrans messageTrans, SessionEventArgs e)
{
TraceLog.Trace("------ OnChatDisconnected -----");
}
void OnWebChatDisconnected(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
TraceLog.Trace("------ OnWebChatDisconnected -----");
}
private void SendLoginToGameServer()
{
CSLoginReq loginReq = new CSLoginReq();
loginReq.Account = m_accountInfo;
loginReq.RealmId = m_GameInfo.RealmId;
loginReq.CheckCode = m_checkcode;
loginReq.Version = m_versionInfo;
//TraceLog.Debug("SendLoginToGameServer start SendMsgToGame! msgId = CSGameMsgID.LoginReq Session : {0} ", GetSessionIDBySessionType(SessionType.GameSession));
SendMsgToGame(loginReq, (int)CSGameMsgID.LoginReq, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.GameSession)));
TraceLog.Debug("请求游戏登录:{0}", m_accountId);
}
void OnWebGameDataReceived(IMessageTransWeb messageTransWeb, WebSessionEventArgs e)
{
MessageData message = e.Message;
GameDataReceived(message);
}
void OnGameDataReceived(IMessageTrans messageTrans, SessionEventArgs e)
{
MessageData message = e.Message;
GameDataReceived(message);
}
void GameDataReceived(MessageData message)
{
RequestPacket packet;
bool result = ProtoPackerFactory.Instance.GetProtoPacker().UnpackMessage(message, out packet);
if (result)
{
// log message
Google.Protobuf.IMessage pbMessage = (Google.Protobuf.IMessage)(packet.Packet);
//TraceLog.Debug("OnGameDataReceived sessionId:{3} recv message from server, message type {0} length {1}#-#{2}"
// , message.Header.Type
// , message.Header.Length
// , pbMessage.ToString()
// , e.Session.SessionID);
if (packet.MsgID == (int)CSGameMsgID.LoginRes)
{
CSLoginRes loginRes = (CSLoginRes)packet.Packet;
if (loginRes.Ret == 0)
{
m_uid = loginRes.Uid;
LoginToken = loginRes.LoginToken;
//TraceLog.Debug("OnGameDataReceived login in game success ,query role info m_uid ={0}", m_uid);
TraceLog.Debug("游戏登录成功:{0} {1}", m_accountId, m_uid);
SendQueryRoleToGameServer();
State = PlayerState.PlayerState_QueryRole;
}
else
{
TraceLog.Debug("OnGameDataReceived uid {0} login fail ret {1}", loginRes.Uid,(CSErrCode)loginRes.Ret);
}
}
else if(packet.MsgID == (int)CSGameMsgID.QueryRoleRes)
{
CSQueryRoleRes roleRes = (CSQueryRoleRes)packet.Packet;
if (roleRes.Ret == 0)
{
lock (LoginCount.lockcount)
{
LoginCount.Count++;
//TraceLog.Debug("OnGameDataReceived get role info from game server success ,enjoy game!");
State = PlayerState.PlayerState_InGame;
DateTime now = DateTime.Now;
int timeCost = (int)(now - this.m_startConnectTime).TotalMilliseconds;
//TraceLog.Debug("OnGameDataReceived Time:{0} get role info from gameserver success, nick {1} level {2} uid {3} accountID {4},-----AllLogin {5}"
// , TimeUtils.GetTime(), roleRes.RoleBase.Nick, roleRes.RoleBase.Level, roleRes.RoleBase.Uid, m_accountId, LoginCount.Count);
//TraceLog.Debug("OnGameDataReceived login cost time {0} millsecond", timeCost);
if(LoginCount.UidAccountIdMap.TryGetValue(m_uid, out string cacheAccountId))
{
if (cacheAccountId != m_accountId)
{
TraceLog.Error("查询角色信息错误 uid:{0} accountId:{1} cacheAccountId:{2}", m_uid, m_accountId, cacheAccountId);
}
}
else
{
LoginCount.UidAccountIdMap.Add(m_uid, m_accountId);
}
TraceLog.Debug("查询角色成功 : {0} {1} cost time {2} millsecond", m_accountId, m_uid, timeCost);
}
//TraceLog.Debug("OnGameDataReceived uid : {0} get role info from game server success ,enjoy game!", m_uid);
m_uid = roleRes.RoleBase.Uid;
m_playerCache.OnInit(roleRes.RoleBase, roleRes.RoleData);
//登录游戏后发个ping,测试一下ping功能
SendPingToGameServer();
//登录chat服务器
//StartConnectChat();
State = PlayerState.PlayerState_InGame;
}
else
{
TraceLog.Debug("OnGameDataReceived QueryRoleRes fail ret {0}", (CSErrCode)roleRes.Ret);
}
}
else if (packet.MsgID == (int)CSGameMsgID.QueryRoleReq)
{
TraceLog.Debug("OnGameDataReceived recv QueryRoleReq " + pbMessage.ToString());
}
else if (packet.MsgID == (int)CSGameMsgID.ChatloginRes)
{
CSChatLoginRes chatLoginRes = (CSChatLoginRes)packet.Packet;
if (chatLoginRes.Ret == 0)
{
IsLoginChat = true;
}
else
{
TraceLog.Debug("OnGameDataReceived recv ChatloginRes fail ret {0}, sessionId : {1}", chatLoginRes.Ret, GetSessionIDBySessionType(SessionType.ChatSession));
}
}
else if (packet.MsgID == (int)CSGameMsgID.ChatRes)
{
CSChatRes chatRes = (CSChatRes)packet.Packet;
TraceLog.Debug("OnGameDataReceived recv chatRes : {0} sessionId : {1}", Convert.ToString(chatRes.Message), GetSessionIDBySessionType(SessionType.ChatSession));
}
else if (packet.MsgID == (int)CSGameMsgID.PlayerQueryOtherRoleInfoRes)
{
CSPlayerQueryOtherRoleInfoRes res = (CSPlayerQueryOtherRoleInfoRes)packet.Packet;
if (res.Ret == 0)
{
TraceLog.Debug("OnGameDataReceived PlayerQueryOtherRoleInfoRes fail ret ");
}
else
{
TraceLog.Debug("OnGameDataReceived PlayerQueryOtherRoleInfoRes fail ret {0}", res.Ret);
}
}
else if (packet.MsgID == (int)CSGameMsgID.QueryRankListRes)
{
CSQueryRankListRes res = (CSQueryRankListRes)packet.Packet;
if (res.Ret == 0)
{
TraceLog.Debug("OnGameDataReceived recv CSQueryRankListRes" + res.ToString());
}
else
{
TraceLog.Debug("OnGameDataReceived recv CSQueryRankListRes fail ret {0}", res.Ret);
}
}
else if (packet.MsgID == (int)CSGameMsgID.Ping)
{
long nowTime = TimeUtils.GetTime();
CSPing pingRes = (CSPing)packet.Packet;
TraceLog.Debug("OnGameDataReceived recv Ping uid:{0}, seq:{1},", m_uid, pingRes.Seq);
/*TraceLog.Debug("OnGameDataReceived recv Ping message from remote:{6}, sessionId:{0}, pingReq:{1}------- clientTime : {2}, serverTime:{3} , nowTime {4}, duration:{5}, uid:{6}",
e.Session.SessionID,
pingRes.Seq,
pingRes.ClientTime,
pingRes.ServerTime,
nowTime,
nowTime - pingRes.ClientTime,
e.Session.RemoteEndPoint);*/
}
else if (packet.MsgID == (int)CSGameMsgID.Chatping)
{
long nowTime = TimeUtils.GetTime();
CSChatPing pingRes = (CSChatPing)packet.Packet;
TraceLog.Debug("-----OnGameDataReceived recv Chatping message from sessionId:{0}, ChatPingSeq:{1} ------- clientTime : {2}, serverTime:{3}, nowTime {4}", GetSessionIDBySessionType(SessionType.ChatSession), pingRes.Seq, pingRes.ClientTime, pingRes.ServerTime, nowTime);
}
else if(packet.MsgID == (int)CSGameMsgID.SystemUnlockInfoChangeSyn)
{
CSSystemUnlockInfoChangeSyn res = (CSSystemUnlockInfoChangeSyn)packet.Packet;
foreach(var id in res.IdList)
{
DBSysUnlockDataOne unlockData = new DBSysUnlockDataOne();
unlockData.SysID = id;
if (this.m_playerCache.m_data != null)
{
this.m_playerCache.m_data.SysUnlockData.SysUnlockDataOne.Add(unlockData);
}
}
}
else
{
//TraceLog.Debug("OnGameDataReceived recv message packet.MsgID is {0}", packet.MsgID);
m_testHandlerMgr.HandlerMsg(packet.MsgID, packet);
}
}
else
{
//TODO 暂时屏蔽了
//TraceLog.Debug("OnGameDataReceived recv message from server, message UnpackMessage Filed!");
}
}
private void SendQueryRoleToGameServer()
{
//TraceLog.Debug("SendQueryRoleToGameServer !");
CSQueryRoleReq queryRoleReq = new CSQueryRoleReq();
queryRoleReq.Uid = m_uid;
SendMsgToGame(queryRoleReq, (int)CSGameMsgID.QueryRoleReq, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.GameSession)));
TraceLog.Debug("请求查询角色:{0} {1}", m_accountId, m_uid);
}
private void SendPingToGameServer()
{
CSPing req = new CSPing();
req.ClientTime = TimeUtils.GetTime();
req.Seq = m_gamePingCount++;
//TraceLog.Debug("SendPingToGameServer ----------------------------- Player [UID] {0} LoginGame Sucess,TestPing sessionID {1} pingReq = {2}-----------------------------"
// , m_uid
// , GetSessionIDBySessionType(SessionType.GameSession)
// , req.Seq);
SendMsgToGame(req, (int)CSGameMsgID.Ping, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.GameSession)));
TraceLog.Debug("游戏ping : {0} {1} seq {2}", m_accountId, m_uid, req.Seq);
m_lastSendtoGameTime = TimeUtils.GetTime();
}
private void SendPingToChatServer()
{
CSChatPing req = new CSChatPing();
long nowTime = TimeUtils.GetTime();
req.ClientTime = nowTime;
req.Seq = m_chatPingCount++;
TraceLog.Debug("SendPingToChatServer ----------------------------- Player [UID] {0} to ChatServer Sucess,TestPing sessionID {1} chatPingReq = {2}-----------------------------"
, m_uid
, GetSessionIDBySessionType(SessionType.ChatSession)
,req.Seq);
SendMsgToChat(req, (int)CSGameMsgID.Chatping, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.ChatSession)));
m_lastChatTime = nowTime;
}
public long GetUid()
{
return m_uid;
}
public void SendGM(string gmstr)
{
CSGmCmd req = new CSGmCmd();
req.CmdStr = gmstr;
SendMsgToGame(req, (int)CSGameMsgID.Gmcmd, Convert.ToUInt32(GetSessionIDBySessionType(SessionType.GameSession)));
}
// public bool IsUnlockSys(int id)
// {
// GetSequenceCheckIndex(id, out int index, out int bytyIndex);
// // if (index >= this.m_playerCache.m_data.SysUnlockData.Check.Count)
// // return false;
// // return CheckInSequence(bytyIndex, m_playerCache.m_data.SysUnlockData.Check[index]);
// }
public static void GetSequenceCheckIndex(int ID, out int index, out int byteIndex)
{
index = (ID - 1) >> 5;
byteIndex = (ID - 1) & 31;
}
public static bool CheckInSequence(int byteIndex, int sequence)
{
return (sequence & (1 << byteIndex)) != 0;
}
public void OnUpdateConnectedSocketError(SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.AccountSession)
{
m_webSessionAccount.OnUpdateConnectedSocketError();
}
else if (sessionType == SessionType.GameSession)
{
m_webSessionGame.OnUpdateConnectedSocketError();
}
else if (sessionType == SessionType.ChatSession)
{
m_webSessionChat.OnUpdateConnectedSocketError();
}
}
else
{
if (sessionType == SessionType.AccountSession)
{
m_sessionAccount.OnUpdateConnectedSocketError();
}
else if (sessionType == SessionType.GameSession)
{
m_sessionGame.OnUpdateConnectedSocketError();
}
else if (sessionType == SessionType.ChatSession)
{
m_sessionChat.OnUpdateConnectedSocketError();
}
}
}
public long GetSessionIDBySessionType(SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.AccountSession)
{
return m_webSessionAccount.m_webSession.SessionID;
}
else if (sessionType == SessionType.GameSession)
{
return m_webSessionGame.m_webSession.SessionID;
}
else if (sessionType == SessionType.ChatSession)
{
return m_webSessionChat.m_webSession.SessionID;
}
}
else
{
if (sessionType == SessionType.AccountSession)
{
return m_sessionAccount.NetSessionObj.SessionID;
}
else if (sessionType == SessionType.GameSession)
{
return m_sessionGame.NetSessionObj.SessionID;
}
else if (sessionType == SessionType.ChatSession)
{
return m_sessionChat.NetSessionObj.SessionID;
}
}
return 0;
}
public bool IsSessionConnected(SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.GameSession)
{
return m_webSessionGame.IsConnected;
}
else if (sessionType == SessionType.ChatSession)
{
return m_webSessionChat.IsConnected;
}
else if (sessionType == SessionType.AccountSession)
{
return m_webSessionAccount.IsConnected;
}
}
else
{
if (sessionType == SessionType.GameSession)
{
return m_sessionGame.IsConnected;
}
else if (sessionType == SessionType.AccountSession)
{
return m_sessionAccount.IsConnected;
}
else if (sessionType == SessionType.ChatSession)
{
return m_sessionChat.IsConnected;
}
}
return false;
}
private void SessionConnect(SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.GameSession)
{
m_webSessionGame.Connect();
}
else if (sessionType == SessionType.ChatSession)
{
m_webSessionChat.Connect();
}
else if (sessionType == SessionType.AccountSession)
{
m_webSessionAccount.Connect();
}
}
else
{
if (sessionType == SessionType.GameSession)
{
m_sessionGame.Connect();
}
else if (sessionType == SessionType.ChatSession)
{
m_sessionChat.Connect();
}
else if (sessionType == SessionType.AccountSession)
{
m_sessionAccount.Connect();
}
}
}
private void SessionReconnect(SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.GameSession)
{
m_webSessionGame.Reconnect();
}
else if (sessionType == SessionType.ChatSession)
{
m_webSessionChat.Reconnect();
}
else if (sessionType == SessionType.AccountSession)
{
m_webSessionAccount.Reconnect();
}
}
else
{
if (sessionType == SessionType.GameSession)
{
m_sessionGame.Reconnect();
}
else if (sessionType == SessionType.ChatSession)
{
m_sessionChat.Reconnect();
}
else if (sessionType == SessionType.AccountSession)
{
m_sessionAccount.Reconnect();
}
}
}
private void UpdateSession(SessionType sessionType, long nowMs)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.GameSession)
{
m_webSessionGame.Update();
}
else if (sessionType == SessionType.ChatSession)
{
m_webSessionChat.Update();
}
else if (sessionType == SessionType.AccountSession)
{
m_webSessionAccount.Update();
}
}
else{
if (sessionType == SessionType.GameSession)
{
m_sessionGame.Update(nowMs);
}
else if (sessionType == SessionType.ChatSession)
{
m_sessionChat.Update(nowMs);
}
else if (sessionType == SessionType.AccountSession)
{
m_sessionAccount.Update(nowMs);
}
}
}
private void SendMessageToSession(MessageData message, SessionType sessionType)
{
if (Config.ClientTestConfig.useGateType == (int)UseGateType.WEBSOCKET)
{
if (sessionType == SessionType.GameSession)
{
m_webSessionGame.Send(message);
}
else if (sessionType == SessionType.ChatSession)
{
m_webSessionChat.Send(message);
}
else if (sessionType == SessionType.AccountSession)
{
m_webSessionAccount.Send(message);
}
else
{
TraceLog.Error($"web SendMessageToSession err! unvaliable sessionType {(int)sessionType}");
}
}
else
{
if (sessionType == SessionType.GameSession)
{
m_sessionGame.Send(message);
}
else if (sessionType == SessionType.ChatSession)
{
m_sessionChat.Send(message);
}
else if (sessionType == SessionType.AccountSession)
{
m_sessionAccount.Send(message);
}
else
{
TraceLog.Error($"SendMessageToSession err! unvaliable sessionType {(int)sessionType}");
}
}
}
private void InitAccountSession(ClientSessionSettings clientSettings)
{
if (Config.ClientTestConfig.useGateType == 1)
{
m_sessionAccount = new UdpClientSession(clientSettings, "Account");
m_sessionAccount.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.AccountSession), m_threadSerial, m_playerCount));
m_sessionAccount.DataReceived += OnAccountMsgReceived;
m_sessionAccount.Disconnected += OnAccDisconnected;
m_sessionAccount.ConnectFail += OnAccountConnectFail;
}
else if (Config.ClientTestConfig.useGateType == 2)
{
m_webSessionAccount = new WebClientSession(clientSettings, m_sessionUpdate);
m_webSessionAccount.m_webSession.ResetSessionID(CalculateSessionId(((int)SessionType.AccountSession), m_threadSerial, m_playerCount));
m_webSessionAccount.DataReceived += OnWebAccountMsgRecied;
m_webSessionAccount.Disconnected += OnWebAccDisconnected;
m_webSessionAccount.ConnectFail += OnWebAccountConnectFail;
}
else
{
m_sessionAccount = new TcpClientSession(clientSettings, m_sessionUpdate, SessionNetSelectMode.Synchronous);
m_sessionAccount.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.AccountSession), m_threadSerial, m_playerCount));
m_sessionAccount.DataReceived += OnAccountMsgReceived;
m_sessionAccount.Disconnected += OnAccDisconnected;
m_sessionAccount.ConnectFail += OnAccountConnectFail;
}
}
private void InitGameSession(ClientSessionSettings clientSettings)
{
if (Config.ClientTestConfig.useGateType == 1)
{
m_sessionGame = new UdpClientSession(clientSettings, "Game");
m_sessionGame.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.GameSession), m_threadSerial, m_playerCount));
m_sessionGame.DataReceived += OnGameDataReceived;
m_sessionGame.Disconnected += OnGameDisconnected;
m_sessionGame.ConnectFail += OnGameConnectFail;
}
else if (Config.ClientTestConfig.useGateType == 2)
{
m_webSessionGame = new WebClientSession(clientSettings, m_sessionUpdate);
m_webSessionGame.m_webSession.ResetSessionID(CalculateSessionId(((int)SessionType.GameSession), m_threadSerial, m_playerCount));
m_webSessionGame.DataReceived += OnWebGameDataReceived;
m_webSessionGame.Disconnected += OnWebGameDisconnected;
m_webSessionGame.ConnectFail += OnWebGameConnectFail;
}
else
{
m_sessionGame = new TcpClientSession(clientSettings, m_sessionUpdate, SessionNetSelectMode.Synchronous);
m_sessionGame.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.GameSession), m_threadSerial, m_playerCount));
m_sessionGame.DataReceived += OnGameDataReceived;
m_sessionGame.Disconnected += OnGameDisconnected;
m_sessionGame.ConnectFail += OnGameConnectFail;
}
}
private void InitChatSession(ClientSessionSettings clientSettings)
{
if (Config.ClientTestConfig.useGateType == 1)
{
m_sessionChat = new UdpClientSession(clientSettings, "Chat");
m_sessionChat.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.ChatSession), m_threadSerial, m_playerCount));
m_sessionChat.DataReceived += OnGameDataReceived;
m_sessionChat.Disconnected += OnChatDisconnected;
}
else if (Config.ClientTestConfig.useGateType == 2)
{
m_webSessionChat = new WebClientSession(clientSettings, m_sessionUpdate);
m_webSessionChat.m_webSession.ResetSessionID(CalculateSessionId(((int)SessionType.ChatSession), m_threadSerial, m_playerCount));
m_webSessionChat.DataReceived += OnWebGameDataReceived;
m_webSessionChat.Disconnected += OnWebChatDisconnected;
}
else
{
m_sessionChat = new TcpClientSession(clientSettings, m_sessionUpdate, SessionNetSelectMode.Synchronous);
m_sessionChat.NetSessionObj.ResetSessionID(CalculateSessionId(((int)SessionType.ChatSession), m_threadSerial, m_playerCount));
m_sessionChat.DataReceived += OnGameDataReceived;
m_sessionChat.Disconnected += OnChatDisconnected;
}
}
private void ReleaseAccountSession()
{
if (m_sessionAccount != null)
{
m_sessionAccount.Dispose();
m_sessionAccount.DataReceived -= OnAccountMsgReceived;
m_sessionAccount.ConnectFail -= OnAccountConnectFail;
m_sessionAccount.Disconnected -= OnAccDisconnected;
}
if (m_webSessionAccount != null)
{
m_webSessionAccount.Dispose();
m_webSessionAccount.DataReceived -= OnWebAccountMsgRecied;
m_webSessionAccount.ConnectFail -= OnWebAccountConnectFail;
m_webSessionAccount.Disconnected -= OnWebAccDisconnected;
}
}
}
}