public Room(Client CT) { RoomOwner = CT; CT.isStayRoom = true; name = CT.socket.RemoteEndPoint.ToString(); index = ServerFunction.MD5(RoomOwner.socket.RemoteEndPoint.ToString()); }
const string Format_finalAttack = "finalAttack@{0}:{1}:{2}"; //参数:对象-掉落个数-击退方向(未单位化) /// <summary> /// 更新数据 /// </summary> /// <param name="paramName"></param> /// <param name="value"></param> public void updateData(string paramName, string value, PlayerData player) { switch (paramName) { case "DValue": int data = int.Parse(value); lastModifyTime_DValue = ServerFunction.getTimeStamp_milSeconds(); //最后一击 if (D_Value >= maxDValue && data > 0) { D_Value = 0.5f * maxDValue; string t = getFinalAttack(player.Pos); msgQueue.Enqueue(t); } D_Value += data; break; case "Score": int data2 = int.Parse(value); //产生消息 string t2 = getSacrifice(this, carryScore, data2); msgQueue.Enqueue(t2); //完成一次献祭 Score += carryScore; carryScore = 0; break; default: break; } }
/// <summary> /// 解析单位行为 /// </summary> /// <param name="msg"></param> /// <param name="player"></param> void ParseUnitBehavious(string msg, PlayerData player) { float time; int camp; string ID; string data = msg.Split(' ')[1]; string[] t = data.Split('@'); time = ServerFunction.SendNumber2Float(t[0]); camp = int.Parse(t[1]); ID = t[2]; //检查行为是否超时 if (time + config.MAXTIME_MSG < Time) { return; } else { //是否合法 if (!UnitDic[camp][ID].isError) { BroadcastMsg(msg); } } }
/// <summary> /// 将事件放入待回答队列 /// </summary> void AddEvent(Event_waitSend t) { Event_waitAnswer t_a = new Event_waitAnswer(); t_a.data = t; t_a.endTime = ServerFunction.getTimeStamp_milSeconds() + maxWaitTime_event; answerEventList.Add(t.index, t_a); }
/// <summary> /// 解析客户端数据 /// </summary> /// <param name="s_data"></param> static void ParseClientData(Client CT, string msg) { string data = msg; string type; try { type = data.Substring(0, 2); } catch { type = ""; } string result = ""; switch (type) { //注册 case "RG": result = AccountManagement.getInstance().Register(data); CT.Send(result); break; //登录 case "LG": result = AccountManagement.getInstance().Login(data); if (result.Split(' ')[1].CompareTo("S") == 0) { CT.ID = result.Split(' ')[2]; CT.isLogin = true; } CT.Send(result); break; //创建房间 case "CR": RoomManagement.getInstance().Parse(CT, data); break; //进入房间 case "ER": RoomManagement.getInstance().Parse(CT, data); break; //心跳 case "HB": CT.updateTick(ServerFunction.getTimeStamp()); break; case "": CT.isLink = false; break; default: break; } }
public void getDamage(int damage, Vector3 shootPos) { lastModifyTime_DValue = ServerFunction.getTimeStamp_milSeconds(); //最后一击 if (D_Value >= maxDValue && damage > 0) { D_Value = 0.5f * maxDValue; string t = getFinalAttack(shootPos); msgQueue.Enqueue(t); } D_Value += damage; }
void Callback_Receive(IAsyncResult ar) { PlayerData player = (PlayerData)ar.AsyncState; try { int t = player.client.socket.EndReceive(ar); if (t == 0) { player.client.isLink = false; return; } } catch { player.client.isLink = false; return; } string data = System.Text.Encoding.UTF8.GetString(player.client.data).TrimEnd('\0'); string[] devideData; //try //{ devideData = ServerFunction.DevideMsg(data); for (int i = 0; i < devideData.Length; i++) { if (devideData[i].CompareTo("HB") != 0 && devideData[i].Substring(0, 2).CompareTo("PD") != 0) { Console.WriteLine("房间内: " + devideData[i]); } Parse(devideData[i], player); } //} //catch //{ // Console.WriteLine("Error Package"); //} //清空数组数据 Array.Clear(player.client.data, 0, player.client.data.Length); if (player.client.isLink && !player.isLeftGameRoom) { try { player.client.socket.BeginReceive(player.client.data, 0, player.client.data.Length, SocketFlags.None, new AsyncCallback(Callback_Receive), player); } catch { } } }
/// <summary> /// 解析单位创造 /// </summary> /// <param name="msg"></param> /// <param name="player"></param> void ParseCreateUnit(string msg, PlayerData player) { Vector3 pos; string rotation; float recoverSpeed; float Time_recover; int MaxDValue; int[] material = new int[3]; int type; int index; string[] data = msg.Split(' ')[1].Split(':'); pos = Vector3.Parse(data[0], ','); rotation = data[1]; recoverSpeed = ServerFunction.SendNumber2Float(data[2]); Time_recover = ServerFunction.SendNumber2Float(data[3]); MaxDValue = int.Parse(data[4]); material[0] = int.Parse(data[5]); material[1] = int.Parse(data[6]); material[2] = int.Parse(data[7]); type = int.Parse(data[8]); //是否能创建 if (!player.isCanCreate(material)) { return; } index = UnitIndex++; UnitInfo t = new UnitInfo(index.ToString(), recoverSpeed, Time_recover, MaxDValue, type, pos, rotation); //添加字典 UnitDic[player.Camp].Add(index.ToString(), t); player.UpdateMaterial(material, -1); //设置委托 t.dele_updateBehavious = UpdateBehavious; //广播 string MSG = string.Format(format_CU, index, data[0], data[1], player.Camp, data[8] ); BroadcastMsg(MSG); }
/// <summary> /// 接收连接回调 /// </summary> /// <param name="ar"></param> static void Callback_Accpet(IAsyncResult ar) { Socket t_socket = (Socket)ar.AsyncState; Client new_Client = new Client(); new_Client.isLink = true; new_Client.socket = t_socket.EndAccept(ar); new_Client.lastTick = ServerFunction.getTimeStamp(); new_Client.IPandPort = new_Client.socket.RemoteEndPoint.ToString(); Console.WriteLine(new_Client.socket.RemoteEndPoint.ToString() + " 连接"); new_Client.socket.BeginReceive(new_Client.data, 0, new_Client.data.Length, SocketFlags.None, new AsyncCallback(Callback_Receive), new_Client); ClientList.Add(new_Client); t_socket.BeginAccept(Callback_Accpet, t_socket); }
/// <summary> /// 接收数据回调 /// 不接收游戏中数据 /// </summary> /// <param name="ar"></param> static void Callback_Receive(IAsyncResult ar) { Client t_client = (Client)ar.AsyncState; try { int t = t_client.socket.EndReceive(ar); if (t == 0) { CloseClient(t_client); return; } } catch { CloseClient(t_client); return; } string data = System.Text.Encoding.UTF8.GetString(t_client.data).TrimEnd('\0'); string[] devideData; try { devideData = ServerFunction.DevideMsg(data); for (int i = 0; i < devideData.Length; i++) { if (devideData[i].CompareTo("HB") != 0) { Console.WriteLine(devideData[i]); } ParseClientData(t_client, devideData[i]); } } catch { Console.WriteLine("Error Package"); } //清空数组数据 Array.Clear(t_client.data, 0, t_client.data.Length); if (t_client.isLink && !t_client.isGame) { t_client.socket.BeginReceive(t_client.data, 0, t_client.data.Length, SocketFlags.None, new AsyncCallback(Callback_Receive), t_client); } }
public GamePlay(Room rm) { name = rm.name; Players = new PlayerData[maxPlayer]; for (int i = 0; i < maxPlayer; i++) { Players[i] = new PlayerData(); } //初始化随机种子 Random rd = new Random(); rand = rd.Next(1, 1000); //初始化玩家数据 Players[0].Camp = 0; Players[0].client = rm.RoomOwner; Players[1].Camp = 1; Players[1].client = rm.OP_client; Players[0].client.socket.BeginReceive(Players[0].client.data, 0, Players[0].client.data.Length, SocketFlags.None, new AsyncCallback(Callback_Receive), Players[0]); Players[1].client.socket.BeginReceive(Players[1].client.data, 0, Players[1].client.data.Length, SocketFlags.None, new AsyncCallback(Callback_Receive), Players[1]); Players[0].client.isGame = true; Players[1].client.isGame = true; Thread_game = new Thread(Game); Thread_game.IsBackground = true; Thread_game.Start(); for (int i = 0; i < maxPlayer; i++) { Players[i].gameplayRoom = this; SendInitData(Players[i]); } for (int i = 0; i < Stronghold.Length; i++) { Stronghold[i] = new StrongholdInfo(); } lastTime = ServerFunction.getTimeStamp_milSeconds(); //初始化单位信息字典 for (int i = 0; i < UnitDic.Length; i++) { UnitDic[i] = new Dictionary <string, UnitInfo>(); } }
/// <summary> /// 更新 /// </summary> public void Update(float deltaTime) { long currentStamp = ServerFunction.getTimeStamp_milSeconds(); //DValue更新 if (lastModifyTime_DValue + config.MaxRecoverTime_DValue < currentStamp) { if (D_Value > 0) { D_Value -= (deltaTime * RecoverRate_DValue); if (D_Value < 0) { D_Value = 0; } if (D_Value > maxDValue) { D_Value = maxDValue; } } } }
/// <summary> /// 检查客户端心跳 /// </summary> static void checkClient() { while (true) { for (int i = ClientList.Count - 1; i >= 0; i--) { if (i >= ClientList.Count) { continue; } long t = ClientList[i].lastTick; //超时 if (ServerFunction.getTimeStamp() - t > maxHeartBeatWaitTime || !ClientList[i].isLink) { CloseClient(ClientList[i]); } } //Console.WriteLine("已连接:" + ClientList.Count); Thread.Sleep(100); } }
const string format_DM = "DM {0}:{1}:{2}:{3}"; //阵营:单位ID:当前DValue:受伤的时间 /// <summary> /// 解析伤害信息 /// </summary> /// <param name="msg"></param> /// <param name="player"></param> void ParseDamageInfo(string msg, PlayerData player) { bool isPlayer; string target; int damage; float time; int camp; Vector3 shootPos; string data = msg.Split(' ')[1]; string[] t = data.Split(':'); isPlayer = (t[0] == "0" ? false : true); target = t[1]; damage = int.Parse(t[2]); time = ServerFunction.SendNumber2Float(t[3]); camp = int.Parse(t[4]); shootPos = Vector3.Parse(t[5], ','); //超时 if (time + config.MAXTIME_MSG < Time) { return; } if (isPlayer) { Players[int.Parse(target)].getDamage(damage, shootPos); } else { float DValue = UnitDic[camp][target].getDamage(damage, Time); //构造广播信息 string sendMSG = string.Format(format_DM, camp, target, ServerFunction.Float2SendNumber(DValue), ServerFunction.Float2SendNumber(Time)); //广播 BroadcastMsg(sendMSG); } }
/// <summary> /// 更新心跳 /// </summary> /// <param name="msg"></param> /// <param name="player"></param> void ParseHeartbeat(string msg, PlayerData player) { player.client.updateTick(ServerFunction.getTimeStamp()); }
/// <summary> /// 游戏 /// </summary> /// <param name="rm"></param> public void Game() { //等待玩家初始化完成 while (true) { int t = 0; for (int i = 0; i < maxPlayer; i++) { if (isReady[i]) { t++; } } if (t == maxPlayer) { //开始游戏 for (int i = 0; i < maxPlayer; i++) { Players[i].client.Send("BG"); } break; } } while (!isFinish) { //更新玩家数据 for (int i = 0; i < Players.Length; i++) { Players[i].Update(deltaTime); } //更新单位状态 if (UpdateBehavious != null) { UpdateBehavious(Time, deltaTime); } //发送玩家事件 int c = 0; string data_1 = "BM"; for (int i = 0; i < Players.Length; i++) { if (Players[i].msgQueue.Count > 0) { data_1 += Players[i].getMsg(); c++; } } if (c > 0) { BroadcastMsg(data_1); } //处理待发事件队列 if (sendEventQueue.Count > 0) { string t_msg = "GE"; while (sendEventQueue.Count > 0) { Event_waitSend t = sendEventQueue.Dequeue(); t_msg += t.ToString(); AddEvent(t); } BroadcastMsg(t_msg); } //处理待回答事件列表 long currentTimeStamp = ServerFunction.getTimeStamp_milSeconds(); if (answerEventList.Count > 0) { Dictionary <int, Event_waitAnswer> .KeyCollection keysCollect = null; keysCollect = answerEventList.Keys; int[] keys = new int[keysCollect.Count]; keysCollect.CopyTo(keys, 0); for (int i = 0; i < keys.Length; i++) { Event_waitAnswer t = answerEventList[keys[i]]; //超时 if (currentTimeStamp > t.endTime) { //如果超过一半玩家应答则予以回应 if (t.getAnswerNum() > maxPlayer * 0.5f) { int t_answer = t.Answer(); string t_data = string.Format("EA {0}:{1}", t.data.selfIndex, t_answer); t.data.client.Send(t_data); } Console.WriteLine("Timeout"); answerEventList.Remove(keys[i]); } } } //获取玩家信息包 string data = "PD "; for (int i = 0; i < Players.Length; i++) { data += (getPlayerData(i)); if (i != Players.Length - 1) { data += "#"; } } //发送玩家信息包 int j = 0; for (int i = 0; i < Players.Length; i++) { if (Players[i].client.isLink) { Players[i].client.Send(data); } else { j++; } } //检测是否所有玩家都已掉线 if (j == maxPlayer) { Console.WriteLine(name + "_房间结束游戏"); isFinish = true; break; } //更新时间参数 deltaTime = (currentTimeStamp - lastTime) / 1000.0f; lastTime = currentTimeStamp; Time += deltaTime; //检测是否结束游戏 int t3 = 0; for (int i = 0; i < Players.Length; i++) { if (Players[i].isEnd) { t3++; } } if (t3 == Players.Length) { //结束游戏 Console.WriteLine(name + "_房间结束游戏"); string data_EG = getEndGameData(); BroadcastMsg(data_EG); break; } Thread.Sleep(50); } while (true) { //检测是否所有玩家都已退出 int j = 0; for (int i = 0; i < Players.Length; i++) { if (!Players[i].client.isLink && !Players[i].isLeftGameRoom) { Players[i].isLeftGameRoom = true; } if (Players[i].isLeftGameRoom) { j++; } } if (j == maxPlayer) { isFinish = true; break; } Thread.Sleep(1000); } }