/// <summary> /// 广播 , 发给所有的客户端 /// </summary> /// <param name="message"></param> public static void Broadcast(IActorMessage message) { Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); foreach (Unit unit in units) { UnitGateComponent unitGateComponent = unit.GetComponent <UnitGateComponent>(); if (unitGateComponent.IsDisconnect) { continue; } ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(unitGateComponent.GateSessionActorId); actorMessageSender.Send(message); } }
/// <summary> /// 广播 /// </summary> /// <param name="message"></param> public static void Broadcast(IActorMessage message) { //获得角色管理组件中所有的角色 Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); //获得Actor会话管理组件 ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); foreach (Unit unit in units) //遍历所有的角色 { UnitGateComponent unitGateComponent = unit.GetComponent <UnitGateComponent>(); //获取每个角色的会话通道 if (unitGateComponent.IsDisconnect) { continue; } //发送消息 ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(unitGateComponent.GateSessionActorId); actorMessageSender.Send(message); } }
protected override async void Run(Session session, G2M_EnterMatch_Landords message) { //Log.Debug("Map服务器收到第一条消息"); LandlordsComponent matchComponent = Game.Scene.GetComponent <LandlordsComponent>(); //玩家是否已经开始游戏 if (matchComponent.Playing.ContainsKey(message.UserID)) { LandlordsRoom room; matchComponent.Playing.TryGetValue(message.UserID, out room); Gamer gamer = room.GetGamerFromUserID(message.UserID); //更新玩家的属性 gamer.ActorIDofUser = message.ActorIDofUser; gamer.ActorIDofClient = message.ActorIDofClient; //帮助玩家恢复牌桌 //向Gate上的User发送匹配成功消息 使User更新绑定的ActorID //Map上的Gamer需要保存User的InstanceID给其发消息 //生成Gamer的时候 需要设置ActorIDofUser ActorMessageSender actorProxy = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(gamer.ActorIDofUser); actorProxy.Send(new Actor_LandlordsMatchSucess() { ActorIDofGamer = gamer.InstanceId }); } else { //新建玩家 Gamer newgamer = ComponentFactory.Create <Gamer, long>(message.UserID); newgamer.ActorIDofUser = message.ActorIDofUser; newgamer.ActorIDofClient = message.ActorIDofClient; //为Gamer添加组件 await newgamer.AddComponent <MailBoxComponent>().AddLocation(); //添加玩家到匹配队列 广播一遍正在匹配中的玩家 matchComponent.AddGamerToMatchingQueue(newgamer); } }
public static void Broadcast(this Tank self, IActorMessage message) { Tank[] tanks = self.Battle.GetAll(); ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); foreach (Tank tank in tanks) { TankGateComponent tankGateComponent = tank.GetComponent <TankGateComponent>(); if (tankGateComponent.IsDisconnect) { continue; } ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(tankGateComponent.GateSessionActorId); actorMessageSender.Send(message); } }
public static async void Start(this TrusteeshipComponent self) { //找到玩家所在房间 LandlordsComponent landordsMatchComponent = Game.Scene.GetComponent <LandlordsComponent>(); Gamer gamer = self.GetParent <Gamer>(); LandlordsRoom room = landordsMatchComponent.GetGamingRoom(self.GetParent <Gamer>()); ActorMessageSender actorProxy = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(gamer.InstanceId); OrderControllerComponent orderController = room.GetComponent <OrderControllerComponent>(); //这个托管组件是通过定时器实现的 while (true) { //延迟1秒 await Game.Scene.GetComponent <TimerComponent>().WaitAsync(3000); if (self.IsDisposed) { return; } if (gamer.UserID != orderController?.CurrentAuthority) { continue; } //给Map上的Gamer发送Actor消息 //自动提示出牌 Actor_GamerPrompt_Back response = (Actor_GamerPrompt_Back)await actorProxy.Call(new Actor_GamerPrompt_Req()); if (response.Error > 0 || response.Cards.Count == 0) { actorProxy.Send(new Actor_GamerDontPlay_Ntt()); } else { await actorProxy.Call(new Actor_GamerPlayCard_Req() { Cards = response.Cards }); } } }
protected override async Task Run(Gamer gamer, Actor_Trusteeship_Ntt message) { Room room = Game.Scene.GetComponent <RoomComponent>().Get(gamer.RoomID); //是否已经托管 bool isTrusteeship = gamer.GetComponent <TrusteeshipComponent>() != null; if (message.isTrusteeship && !isTrusteeship) { gamer.AddComponent <TrusteeshipComponent>(); Log.Info($"玩家{gamer.UserID}切换为自动模式"); } else if (isTrusteeship) { gamer.RemoveComponent <TrusteeshipComponent>(); Log.Info($"玩家{gamer.UserID}切换为手动模式"); } //这里由服务端设置消息UserID用于转发 Actor_Trusteeship_Ntt transpond = new Actor_Trusteeship_Ntt(); transpond.isTrusteeship = message.isTrusteeship; transpond.UserID = gamer.UserID; //转发消息 room.Broadcast(transpond); if (isTrusteeship) { OrderControllerComponent orderController = room.GetComponent <OrderControllerComponent>(); if (gamer.UserID == orderController.CurrentAuthority) { bool isFirst = gamer.UserID == orderController.Biggest; ActorMessageSender actorProxy = gamer.GetComponent <UnitGateComponent>().GetActorMessageSender(); actorProxy.Send(new Actor_AuthorityPlayCard_Ntt() { UserID = orderController.CurrentAuthority, IsFirst = isFirst }); } } await Task.CompletedTask; }
protected override void Run(Session session, C2G_ReturnLobby_Ntt message) { //验证Session if (!GateHelper.SignSession(session)) { return; } User user = session.GetComponent <SessionUserComponent>().User; StartConfigComponent config = Game.Scene.GetComponent <StartConfigComponent>(); ActorMessageSenderComponent actorProxyComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); //通知Map服务器玩家离开房间 if (user.ActorIDforClient != 0) { ActorMessageSender actorProxy = actorProxyComponent.Get(user.ActorIDforClient); actorProxy.Send(new Actor_PlayerExitRoom()); user.ActorIDforClient = 0; } }
protected override async ETTask Run(Session session, C2G_ReadyLand_Ntt message) { //验证Session if (!GateHelper.SignSession(session)) { return; } User user = session.GetComponent <SessionUserComponent>().User; StartConfigComponent config = Game.Scene.GetComponent <StartConfigComponent>(); ActorMessageSenderComponent actorProxyComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); //通知Map服务器玩家准备游戏 if (user.ActorID != 0) { ActorMessageSender actorProxy = actorProxyComponent.Get(user.ActorID); actorProxy.Send(new Actor_GamerReady_Landlords()); user.ActorID = 0; } await ETTask.CompletedTask; }
protected override async ETTask Run(Session session, EnterMatchs_G2M message) { //Log.Debug("Map服务器收到第一条消息"); LandMatchComponent matchComponent = Game.Scene.GetComponent <LandMatchComponent>(); //玩家是否在房间中待机 if (matchComponent.Waiting.ContainsKey(message.UserID)) { Room room; //通过UserID获取matchComponent中相对应的键,即找到此User所在的Room matchComponent.Waiting.TryGetValue(message.UserID, out room); //房间中的玩家对象,获取获取其UserID的座位索引 Gamer gamer = room.GetGamerFromUserID(message.UserID); //设置GateActorID,ClientActorID gamer.GActorID = message.GActorID; gamer.CActorID = message.CActorID; //向Gate发送消息更新Gate上user的ActorID //这样不论玩家到了哪个地图服务器,Gate上的user都持有所在地图服务器上gamer的InstanceId ActorMessageSender actorProxy = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(gamer.GActorID); actorProxy.Send(new Actor_MatchSucess_M2G() { GamerID = gamer.InstanceId }); } else { //新建玩家,用UserID构建Gamer Gamer newgamer = ComponentFactory.Create <Gamer, long>(message.UserID); newgamer.GActorID = message.GActorID; newgamer.CActorID = message.CActorID; //为Gamer添加MailBoxComponent组件,可以通过MailBox进行actor通信 await newgamer.AddComponent <MailBoxComponent>().AddLocation(); //添加玩家到匹配队列 广播一遍正在匹配中的玩家 matchComponent.AddGamerToMatchingQueue(newgamer); } }
public static void BroadcastTarget(IActorMessage message, List <long> targetUids) { ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); for (int i = 0; i < targetUids?.Count; i++) { if (targetUids[i] <= 0) { Log.Error($"BroadcastTargetg失敗! targetUid<=0 {message.ToString()}"); continue; } Player player = CacheHelper.GetFromCache <Player>(targetUids[i]); if (player == null || !player.isOnline || player.gateSessionActorId == 0) { Log.Trace($"Don't broadcast player who have disconnected!"); continue; } ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(player.gateSessionActorId); actorMessageSender.Send(message); } }
public override async void Destroy(SessionUserComponent self) { //释放User对象时将User对象从管理组件中移除 Game.Scene.GetComponent <UserComponent>()?.Remove(self.User.UserID); StartConfigComponent config = Game.Scene.GetComponent <StartConfigComponent>(); //正在匹配中发送玩家退出匹配请求 if (self.User.IsMatching) { // IPEndPoint matchIPEndPoint = config.MatchConfig.GetComponent<InnerConfig>().IPEndPoint; // Session matchSession = Game.Scene.GetComponent<NetInnerComponent>().Get(matchIPEndPoint); // await matchSession.Call(new G2M_PlayerExitMatch_Req() { UserID = this.User.UserID }); } //正在游戏中发送玩家退出房间请求 if (self.User.ActorID != 0) { Log.Info($"session释放,玩家MapId:{self.User.ActorID}"); ActorMessageSenderComponent actorMessageSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); ActorMessageSender actorMessageSender = actorMessageSenderComponent.Get(self.User.ActorID); actorMessageSender.Send(new Actor_GamerExitRoom() { IsFromClient = false, }); } //向登录服务器发送玩家下线消息 // IPEndPoint realmIPEndPoint = config.RealmConfig.GetComponent<InnerConfig>().IPEndPoint; // Session realmSession = Game.Scene.GetComponent<NetInnerComponent>().Get(realmIPEndPoint); // realmSession.Send(new Actor_ForceOffline()); self.User.Dispose(); self.User = null; }
protected override async void Run(Gamer gamer, Actor_Trusteeship_Ntt message) { LandlordsRoom room = Game.Scene.GetComponent <LandlordsComponent>().GetGamingRoom(gamer); //是否已经托管 bool isTrusteeship = gamer.GetComponent <TrusteeshipComponent>() != null; if (message.IsTrusteeship && !isTrusteeship) { gamer.AddComponent <TrusteeshipComponent>(); Log.Info($"玩家{gamer.UserID}切换为自动模式"); } else if (isTrusteeship) { gamer.RemoveComponent <TrusteeshipComponent>(); Log.Info($"玩家{gamer.UserID}切换为手动模式"); } //当玩家切换为手动模式时 补发出牌权 if (isTrusteeship) { OrderControllerComponent orderController = room.GetComponent <OrderControllerComponent>(); if (gamer.UserID == orderController.CurrentAuthority) { bool isFirst = gamer.UserID == orderController.Biggest; //向客户端发送出牌权消息 ActorMessageSender actorProxy = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(gamer.ActorIDofClient); actorProxy.Send(new Actor_AuthorityPlayCard_Ntt() { UserID = orderController.CurrentAuthority, IsFirst = isFirst }); } } await Task.CompletedTask; }
protected override async Task Run(Room room, Actor_PlayerEnterRoom_Req message, Action <Actor_PlayerEnterRoom_Ack> reply) { Actor_PlayerEnterRoom_Ack response = new Actor_PlayerEnterRoom_Ack(); try { Gamer gamer = room.Get(message.UserID); if (gamer == null) { //创建房间玩家对象 gamer = GamerFactory.Create(message.PlayerID, message.UserID); await gamer.AddComponent <MailBoxComponent>().AddLocation(); gamer.AddComponent <UnitGateComponent, long>(message.SessionID); //加入到房间 room.Add(gamer); Actor_GamerEnterRoom_Ntt broadcastMessage = new Actor_GamerEnterRoom_Ntt(); foreach (Gamer _gamer in room.GetAll()) { if (_gamer == null) { //添加空位 broadcastMessage.Gamers.Add(null); continue; } //添加玩家信息 GamerInfo info = new GamerInfo() { UserID = _gamer.UserID, IsReady = _gamer.IsReady }; broadcastMessage.Gamers.Add(info); } //广播房间内玩家消息 room.Broadcast(broadcastMessage); Log.Info($"玩家{message.UserID}进入房间"); } else { //玩家重连 gamer.isOffline = false; gamer.PlayerID = message.PlayerID; gamer.GetComponent <UnitGateComponent>().GateSessionActorId = message.SessionID; //玩家重连移除托管组件 gamer.RemoveComponent <TrusteeshipComponent>(); Actor_GamerEnterRoom_Ntt broadcastMessage = new Actor_GamerEnterRoom_Ntt(); foreach (Gamer _gamer in room.GetAll()) { if (_gamer == null) { //添加空位 broadcastMessage.Gamers.Add(null); continue; } //添加玩家信息 GamerInfo info = new GamerInfo() { UserID = _gamer.UserID, IsReady = _gamer.IsReady }; broadcastMessage.Gamers.Add(info); } //发送房间玩家信息 ActorMessageSender actorProxy = gamer.GetComponent <UnitGateComponent>().GetActorMessageSender(); actorProxy.Send(broadcastMessage); List <GamerCardNum> gamersCardNum = new List <GamerCardNum>(); List <GamerState> gamersState = new List <GamerState>(); GameControllerComponent gameController = room.GetComponent <GameControllerComponent>(); OrderControllerComponent orderController = room.GetComponent <OrderControllerComponent>(); DeskCardsCacheComponent deskCardsCache = room.GetComponent <DeskCardsCacheComponent>(); foreach (Gamer _gamer in room.GetAll()) { HandCardsComponent handCards = _gamer.GetComponent <HandCardsComponent>(); gamersCardNum.Add(new GamerCardNum() { UserID = _gamer.UserID, Num = _gamer.GetComponent <HandCardsComponent>().GetAll().Length }); gamersState.Add(new GamerState() { UserID = _gamer.UserID, Identity = (byte)handCards.AccessIdentity, GrabLandlordState = orderController.GamerLandlordState.ContainsKey(_gamer.UserID) ? orderController.GamerLandlordState[_gamer.UserID] : false }); } //发送游戏开始消息 Actor_GameStart_Ntt gameStartNotice = new Actor_GameStart_Ntt() { HandCards = gamer.GetComponent <HandCardsComponent>().GetAll(), GamersCardNum = gamersCardNum }; actorProxy.Send(gameStartNotice); Card[] lordCards = null; if (gamer.GetComponent <HandCardsComponent>().AccessIdentity == Identity.None) { //广播先手玩家 actorProxy.Send(new Actor_AuthorityGrabLandlord_Ntt() { UserID = orderController.CurrentAuthority }); } else { if (gamer.UserID == orderController.CurrentAuthority) { //发送可以出牌消息 bool isFirst = gamer.UserID == orderController.Biggest; actorProxy.Send(new Actor_AuthorityPlayCard_Ntt() { UserID = orderController.CurrentAuthority, IsFirst = isFirst }); } lordCards = deskCardsCache.LordCards.ToArray(); } //发送重连数据 Actor_GamerReconnect_Ntt reconnectNotice = new Actor_GamerReconnect_Ntt() { Multiples = room.GetComponent <GameControllerComponent>().Multiples, GamersState = gamersState, DeskCards = new KeyValuePair <long, Card[]>(orderController.Biggest, deskCardsCache.library.ToArray()), LordCards = lordCards, }; actorProxy.Send(reconnectNotice); Log.Info($"玩家{message.UserID}重连"); } response.GamerID = gamer.Id; reply(response); } catch (Exception e) { ReplyError(response, e, reply); } }
protected override async Task Run(Gamer gamer, Actor_GamerExitRoom message) { try { Log.Info($"玩家{gamer.UserID}退出房间"); RoomComponent roomComponent = Game.Scene.GetComponent <RoomComponent>(); Room room = roomComponent.Get(gamer.RoomID); if (room == null) { return; } if (room.State == RoomState.Game) { if (gamer.isOffline) { return; } gamer.isOffline = true; //玩家断开添加自动出牌组件 //if (gamer.GetComponent<TrusteeshipComponent>() == null) //gamer.AddComponent<TrusteeshipComponent>(); gamer.EndTime = DateTime.Now; TimeSpan span = gamer.EndTime - gamer.StartTime; int totalSeconds = (int)span.TotalSeconds; //await DBCommonUtil.RecordGamerTime(gamer.EndTime, false,gamer.UserID); await DBCommonUtil.RecordGamerInfo(gamer.UserID, totalSeconds); Log.Info($"玩家{gamer.UserID}断开,切换为自动模式"); } else { GameControllerComponent gameControllerComponent = room.GetComponent <GameControllerComponent>(); //好友房还没开局房主掉线,房间解散 if (room.IsFriendRoom && room.State == RoomState.Idle && room.CurrentJuCount == 0) { if (gameControllerComponent.RoomConfig.MasterUserId == gamer.UserID) { room.Broadcast(new Actor_GamerReadyTimeOut() { Message = "房主解散房间" }); GameHelp.RoomDispose(room); return; } } //好友房开局后,掉线后不能退出 if (room.IsFriendRoom && room.CurrentJuCount > 0 && room.CurrentJuCount < gameControllerComponent.RoomConfig.JuCount) { gamer.isOffline = true; Log.Info($"{gamer.UserID} 好友房开局后,掉线后不能退出"); return; } //玩家主动退出 通知gate if (message.IsFromClient) { ActorMessageSenderComponent actorMessageSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); ActorMessageSender actorMessageSender = actorMessageSenderComponent.Get(gamer.PlayerID); actorMessageSender.Send(new M2G_Actor_GamerExitRoom()); //消息广播给其他人 room.Broadcast(new Actor_GamerExitRoom() { Uid = gamer.UserID }); //房间移除玩家 Log.Info($"{gamer.UserID}主动退出,移除玩家"); room.Remove(gamer.UserID); } else //游戏崩溃 { //房间移除玩家 Log.Info($"{gamer.UserID}崩溃退出,移除玩家"); room.Remove(gamer.UserID); //消息广播给其他人 room.Broadcast(new Actor_GamerExitRoom() { Uid = gamer.UserID }); } gamer.Dispose(); //房间没人就释放 if (room.seats.Count == 0) { roomComponent.RemoveRoom(room); room?.Dispose(); } } } catch (Exception e) { Log.Error(e); } await Task.CompletedTask; }
/// <summary> /// 准备开始游戏 /// </summary> /// <param name="self"></param> public static void ReadyStartGame(this GameControllerComponent self) { Room room = self.GetParent <Room>(); Gamer[] gamers = room.GetAll(); //房间内有3名玩家且全部准备则开始游戏 if (room.Count == 3 && gamers.Where(g => g.IsReady).Count() == 3) { //同步匹配服务器开始游戏 room.State = RoomState.Game; MapHelper.SendMessage(new MP2MH_SyncRoomState_Ntt() { RoomID = room.Id, State = room.State }); //初始玩家开始状态 foreach (var _gamer in gamers) { if (_gamer.GetComponent <HandCardsComponent>() == null) { _gamer.AddComponent <HandCardsComponent>(); } _gamer.IsReady = false; } GameControllerComponent gameController = room.GetComponent <GameControllerComponent>(); //洗牌发牌 gameController.DealCards(); List <GamerCardNum> gamersCardNum = new List <GamerCardNum>(); Array.ForEach(gamers, (g) => { HandCardsComponent handCards = g.GetComponent <HandCardsComponent>(); //重置玩家身份 handCards.AccessIdentity = Identity.None; //记录玩家手牌数 gamersCardNum.Add(new GamerCardNum() { UserID = g.UserID, Num = g.GetComponent <HandCardsComponent>().GetAll().Length }); }); //发送玩家手牌和其他玩家手牌数 foreach (var _gamer in gamers) { ActorMessageSender actorProxy = _gamer.GetComponent <UnitGateComponent>().GetActorMessageSender(); actorProxy.Send(new Actor_GameStart_Ntt() { HandCards = _gamer.GetComponent <HandCardsComponent>().GetAll(), GamersCardNum = gamersCardNum }); } //随机先手玩家 gameController.RandomFirstAuthority(); Log.Info($"房间{room.Id}开始游戏"); } }
protected override async ETTask Run(Gamer gamer, Actor_GamerGrabLandlordSelect_Ntt message) { Room room = Game.Scene.GetComponent <LandMatchComponent>().GetGamingRoom(gamer); OrderControllerComponent orderController = room.GetComponent <OrderControllerComponent>(); GameControllerComponent gameController = room.GetComponent <GameControllerComponent>(); ActorMessageSenderComponent actorProxyComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); if (orderController.CurrentAuthority == gamer.UserID) { //保存抢地主状态 orderController.GamerLandlordState[gamer.UserID] = message.IsGrab; if (message.IsGrab) { orderController.Biggest = gamer.UserID; gameController.Multiples *= 2; room.Broadcast(new Actor_SetMultiples_Ntt() { Multiples = gameController.Multiples }); } //转发消息 Actor_GamerGrabLandlordSelect_Ntt transpond = new Actor_GamerGrabLandlordSelect_Ntt(); transpond.IsGrab = message.IsGrab; transpond.UserID = gamer.UserID; room.Broadcast(transpond); //房间有三人抢地主操作后(抢或不抢) if (orderController.SelectLordIndex >= room.Count) { /* * 地主:√ 农民1:× 农民2:× * 地主:× 农民1:√ 农民2:√ * 地主:√ 农民1:√ 农民2:√ 地主:√ * * */ if (orderController.Biggest == 0) { //没人抢地主则重新发牌 gameController.BackToDeck(); gameController.DealCards(); //发送玩家手牌 Gamer[] gamers = room.gamers; List <GamerCardNum> gamersCardNum = new List <GamerCardNum>(); Array.ForEach(gamers, _gamer => gamersCardNum.Add(new GamerCardNum() { UserID = _gamer.UserID, Num = _gamer.GetComponent <HandCardsComponent>().GetAll().Length })); Array.ForEach(gamers, _gamer => { ActorMessageSender actorProxy = actorProxyComponent.Get(_gamer.CActorID); actorProxy.Send(new Actor_GameStartHandCards_Ntt() { HandCards = To.RepeatedField(_gamer.GetComponent <HandCardsComponent>().GetAll()), GamersCardNum = To.RepeatedField(gamersCardNum) }); }); //随机先手玩家 gameController.RandomFirstAuthority(); return; } else if ((orderController.SelectLordIndex == room.Count && ((orderController.Biggest != orderController.FirstAuthority.Key && !orderController.FirstAuthority.Value) || orderController.Biggest == orderController.FirstAuthority.Key)) || orderController.SelectLordIndex > room.Count) { gameController.CardsOnTable(orderController.Biggest); return; } } //当所有玩家都抢地主时先手玩家还有一次抢地主的机会 if (gamer.UserID == orderController.FirstAuthority.Key && message.IsGrab) { orderController.FirstAuthority = new KeyValuePair <long, bool>(gamer.UserID, true); } orderController.Turn(); orderController.SelectLordIndex++; room.Broadcast(new Actor_AuthorityGrabLandlord_Ntt() { UserID = orderController.CurrentAuthority }); } await ETTask.CompletedTask; }
public async void Dispatch(Session session, Packet packet) { object message; try { OpcodeTypeComponent opcodeTypeComponent = session.Network.Entity.GetComponent <OpcodeTypeComponent>(); object instance = opcodeTypeComponent.GetInstance(packet.Opcode); message = session.Network.MessagePacker.DeserializeFrom(instance, packet.Stream); } catch (Exception e) { // 出现任何异常都要断开Session,防止客户端伪造消息 Log.Error(e); session.Error = ErrorCode.ERR_PacketParserError; session.Network.Remove(session.Id); return; } //Log.Debug($"recv: {JsonHelper.ToJson(message)}"); switch (message) { case IFrameMessage iFrameMessage: // 如果是帧消息,构造成OneFrameMessage发给对应的unit { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); // 这里设置了帧消息的id,防止客户端伪造 iFrameMessage.Id = unitId; OneFrameMessage oneFrameMessage = new OneFrameMessage { Op = packet.Opcode, AMessage = ByteString.CopyFrom(session.Network.MessagePacker.SerializeTo(iFrameMessage)) }; actorMessageSender.Send(oneFrameMessage); return; } case IActorRequest iActorRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); int rpcId = iActorRequest.RpcId; // 这里要保存客户端的rpcId IResponse response = await actorMessageSender.Call(iActorRequest); response.RpcId = rpcId; session.Reply(response); return; } case IActorMessage iActorMessage: // gate session收到actor消息直接转发给actor自己去处理 { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); actorMessageSender.Send(iActorMessage); return; } } Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, new MessageInfo(packet.Opcode, message)); }
/// <summary> /// 准备开始游戏 /// </summary> /// <param name="self"></param> public static async void ReadyStartGame(this GameControllerComponent self) { Room room = self.GetParent <Room>(); Gamer[] gamers = room.GetAll(); if (room.State == RoomState.Game) { DeckComponent deck = room.GetComponent <DeckComponent>(); Log.Info($"当前准备的玩家个数:{deck.XJReady}"); if (deck.XJReady == self.Config.PlayerCount) { Log.Info("重新开始游戏"); //重置庄 foreach (Gamer gamer in gamers) { gamer.IsRobBanker = false; gamer.GetComponent <HandCardsComponent>().Reset(); } //重新洗牌 self.DealCards(); //清理缓存数据 deck.Reset(); //发送游戏开始 room.Broadcast(new Actor_GamerStart_Ntt()); await Game.Scene.GetComponent <TimerComponent>().WaitAsync(1000); //发送手牌 foreach (var _gamer in gamers) { ActorMessageSender actorProxy = _gamer.GetComponent <UnitGateComponent>().GetActorMessageSender(); actorProxy.Send(new Actor_SendCard_Ntt() { Cards = _gamer.GetComponent <HandCardsComponent>().GetAll() }); Log.Info($"{_gamer.UserID}手牌:{_gamer.GetComponent<HandCardsComponent>().ShowAllCard()}"); } await Game.Scene.GetComponent <TimerComponent>().WaitAsync(1000); } } if (room.State == RoomState.Idle) { if (room.Count == self.Config.PlayerCount && gamers.Count(model => model.IsReady) == self.Config.PlayerCount) { room.State = RoomState.Game; //所有玩家准备!! //发送游戏开始 room.Broadcast(new Actor_GamerStart_Ntt()); await Game.Scene.GetComponent <TimerComponent>().WaitAsync(1000); self.DealCards(); foreach (var _gamer in gamers) { ActorMessageSender actorProxy = _gamer.GetComponent <UnitGateComponent>().GetActorMessageSender(); actorProxy.Send(new Actor_SendCard_Ntt() { Cards = _gamer.GetComponent <HandCardsComponent>().GetAll() }); Log.Info($"{_gamer.UserID}手牌:{_gamer.GetComponent<HandCardsComponent>().ShowAllCard()}"); } await Game.Scene.GetComponent <TimerComponent>().WaitAsync(1000); Log.Info("可以开始出牌了"); } } }
public async void Dispatch(Session session, Packet packet) { Log.Debug("分配消息" + packet.Opcode); IMessage message; try { message = session.Network.Entity.GetComponent <OpcodeTypeComponent>().GetNewMessage(packet.Opcode); message.MergeFrom(packet.Bytes, packet.Offset, packet.Length); //message = session.Network.MessagePacker.DeserializeFrom(messageType, packet.Bytes, Packet.Index, packet.Length - Packet.Index); } catch (Exception e) { // 出现任何异常都要断开Session,防止客户端伪造消息 Log.Error(e); session.Error = ErrorCode.ERR_PacketParserError; session.Network.Remove(session.Id); return; } //Log.Debug($"recv: {JsonHelper.ToJson(message)}"); switch (message) { case IFrameMessage iFrameMessage: // 如果是帧消息,构造成OneFrameMessage发给对应的unit { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); // 这里设置了帧消息的id,防止客户端伪造 iFrameMessage.Id = unitId; //OneFrameMessage oneFrameMessage = new OneFrameMessage //{ // Op = packet.Opcode, // AMessage = session.Network.MessagePacker.SerializeToByteArray(iFrameMessage) //}; //actorMessageSender.Send(oneFrameMessage); return; } case IActorRequest iActorRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); int rpcId = iActorRequest.RpcId; // 这里要保存客户端的rpcId IResponse response = await actorMessageSender.Call(iActorRequest); response.RpcId = rpcId; session.Reply(response); return; } case IActorMessage iActorMessage: // gate session收到actor消息直接转发给actor自己去处理 { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(unitId); actorMessageSender.Send(iActorMessage); return; } } Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, new MessageInfo(packet.Opcode, message)); }
public async void Dispatch(Session session, ushort opcode, object message) { try { SessionHeartbeatComponent sessionHeartbeatComponent = session.GetComponent <SessionHeartbeatComponent>(); SessionUserComponent sessionUserComponent = session.GetComponent <SessionUserComponent>(); if (sessionHeartbeatComponent == null) { session.Dispose();//心跳组件 没有 直接销毁 return; } sessionHeartbeatComponent.UpReceiveMessageDistance = 0;//重置上次收到消息的时间 //如果没有挂载SessionUserComponent组件 需要判断一下是不是登陆消息 if (sessionUserComponent == null) { if (message.GetType() != typeof(C2G_GateLogin) && message.GetType() != typeof(C2R_CommonLogin)) { session.Dispose(); //发其他 消息 却没有 SessionUserComponent 组件 绝对不走正常 return; } } //如果收到 一秒收到的消息 大于规定的消息 就认定是DOSS攻击 直接销毁 if (++sessionHeartbeatComponent.SecondTotalMessageNum >= SessionHeartbeatComponent.DestroySeesiontSecondTotalNum) { //断开连接 sessionHeartbeatComponent.DisposeSession(); //直接封号 // UserHelp.StopSealOrRelieve(sessionUserComponent.UserId,true,"DOSS攻击封号"); //不要封号容易误封 return; } switch (message) { case IActorMessage irActorMessage: { long sessionActorId = sessionUserComponent.GamerSessionActorId; if (sessionActorId == 0) { return; } ActorMessageSender actorLocationSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(sessionActorId); actorLocationSender.Send(irActorMessage); return; } case IUserRequest iUserRequest: { if (iUserRequest is IUserActorRequest userActorRequest) { userActorRequest.SessionActorId = session.Id; userActorRequest.User = sessionUserComponent.user; } if (iUserRequest is IAdministratorRequest administratorRequest) { if (!AdministratorHelp.VerifyAdministrator(administratorRequest)) { //如果账号密码错误 直接返回 不如直接封号 return; } } iUserRequest.UserId = sessionUserComponent.UserId; AppType appType = (AppType)(1 << ((opcode - 10000) / 1000)); Session serverSession = Game.Scene.GetComponent <NetInnerSessionComponent>().Get(appType); int rpcId = iUserRequest.RpcId; // 这里要保存客户端的rpcId IResponse response = await serverSession.Call(iUserRequest); response.RpcId = rpcId; session.Reply(response); return; } case C2G_Heartbeat c2GHeartbeat: return; } Game.Scene.GetComponent <MessageDispatherComponent>().Handle(session, new MessageInfo(opcode, message)); } catch (Exception e) { Log.Error(e); } }
public async ETVoid DispatchAsync(Session session, ushort opcode, object message) { // 根据消息接口判断是不是Actor消息,不同的接口做不同的处理 switch (message) { case IFrameMessage iFrameMessage: // 如果是帧消息,构造成OneFrameMessage发给对应的unit { // ... return; } case IActorLocationRequest actorLocationRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long unitId = session.GetComponent <SessionUserComponent>().User.UnitId; ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId); int rpcId = actorLocationRequest.RpcId; // 这里要保存客户端的rpcId long instanceId = session.InstanceId; IResponse response = await actorLocationSender.Call(actorLocationRequest); response.RpcId = rpcId; // session可能已经断开了,所以这里需要判断 if (session.InstanceId == instanceId) { session.Reply(response); } break; } case IActorLocationMessage actorLocationMessage: { long unitId = session.GetComponent <SessionUserComponent>().User.UnitId; ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId); actorLocationSender.Send(actorLocationMessage); break; } case IActorRequest iActorRequest: { long actorId = session.GetComponent <SessionUserComponent>().User.ActorId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(actorId); int rpcId = iActorRequest.RpcId; // 这里要保存客户端的rpcId IResponse response = await actorMessageSender.Call(iActorRequest); response.RpcId = rpcId; session.Reply(response); return; } case IActorMessage iActorMessage: { long actorId = session.GetComponent <SessionUserComponent>().User.ActorId; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(actorId); actorMessageSender.Send(iActorMessage); return; } default: { // 非Actor消息 Game.Scene.GetComponent <MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message)); break; } } }
protected override async ETTask Run(Session session, CreateUnit_G2M message) { // 查询玩家角色信息中是否已有地图与位置坐标数据 // ... Unit unit = ComponentFactory.CreateWithId <Unit>(IdGenerater.GenerateId()); unit.GActorId = message.GActorId; unit.CActorId = message.CActorId; unit.Position = new Vector3(-10, 0, -10); // 给unit添加unit状态组件与角色移动组件 unit.AddComponent <UnitStateComponent>(); unit.AddComponent <CharacterMoveComponent>(); // unit添加到UnitComponet,添加MailBoxComponent await unit.AddComponent <MailBoxComponent>().AddLocation(); Game.Scene.GetComponent <UnitComponent>().Add(unit); //创建地图房间的玩家,用UserID构建Gamer Gamer gamer = ComponentFactory.Create <Gamer, long>(message.UserId); gamer.GActorId = message.GActorId; gamer.CActorId = message.CActorId; // 更新gamer的UnitId gamer.UnitId = unit.Id; gamer.CharaId = message.CharaId; //为Gamer添加组件 await gamer.AddComponent <MailBoxComponent>().AddLocation(); //更新网关user的ActorID ActorMessageSender actorProxy = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(gamer.GActorId); actorProxy.Send(new Actor_EnterMapSucess_M2G() { GamerId = gamer.InstanceId, UnitId = unit.Id }); // 将gamer添加到地图房间 RoomComponent roomComponent = Game.Scene.GetComponent <RoomComponent>(); Room room = roomComponent.GetMapRoom(1001); // 暂时用黎明镇的地图编号 room.Add(gamer); unit.gamer = gamer; unit.room = room; // 广播创建的units CreateUnits_M2C createUnits = new CreateUnits_M2C(); Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); foreach (Unit u in units) { UnitInfo unitInfo = new UnitInfo(); unitInfo.X = u.Position.x; unitInfo.Y = u.Position.y; unitInfo.Z = u.Position.z; unitInfo.UnitId = u.Id; unitInfo.UserId = u.gamer.UserId; unitInfo.CharaId = u.gamer.CharaId; createUnits.Units.Add(unitInfo); } // 应该是只向玩家可见范围的其它玩家广播,目前还没实现暂时向整个地图房间广播 room.Broadcast(createUnits); }
public async ETVoid UpDateNetSync(long ttk) { while (true) { await timerComponent.WaitAsync(ttk); List <Unit> units = unitComponent.getCountUnits(0); if (units != null) { ActorMessageSenderComponent actorSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); List <BulletInfo> bulletInfos = bulletManagerComponent.GetAllNeedSyncBullet(); for (int i = 0; i < units.Count; i++) { ActorMessageSender actorMessageSender = actorSenderComponent.Get(units[i].GateInstanceId); List <int> accounts = new List <int>(); List <float> positionX = new List <float>(); List <float> positionY = new List <float>(); List <float> positionZ = new List <float>(); List <float> rotationX = new List <float>(); List <float> rotationY = new List <float>(); List <float> rotationZ = new List <float>(); List <float> rotationW = new List <float>(); List <float> velocityX = new List <float>(); List <float> velocityY = new List <float>(); List <float> velocityZ = new List <float>(); List <bool> isFire = new List <bool>(); for (int j = 0; j < units.Count; j++) { //这个单位没有死亡 if (!units[j].Die) { //并且不是自己 if (units[i].Account != units[j].Account) { accounts.Add(units[j].Account); positionX.Add(units[j].InitPositionX); positionY.Add(units[j].InitPositionY); positionZ.Add(units[j].InitPositionZ); rotationX.Add(units[j].RotationX); rotationY.Add(units[j].RotationY); rotationZ.Add(units[j].RotationZ); rotationW.Add(units[j].RotationW); velocityX.Add(units[j].VelocityX); velocityY.Add(units[j].VelocityY); velocityZ.Add(units[j].VelocityZ); isFire.Add(units[j].Fire); } } } actorMessageSender.Send(new Actor_PlayerNetSyncToCline() { DirAccount = accounts, PositionX = positionX, PositionY = positionY, PositionZ = positionZ, RotationX = rotationX, RotationY = rotationY, RotationZ = rotationZ, RotationW = rotationW, VelocityX = velocityX, VelocityY = velocityY, VelocityZ = velocityZ, Fire = isFire, Bullets = bulletInfos, }); } } } }
protected override async ETTask Run(MapUnit mapUnit, C2M_TeamRun message, Action <M2C_TeamRun> reply) { await ETTask.CompletedTask; M2C_TeamRun response = new M2C_TeamRun(); try { if (mapUnit.Room == null) { response.Error = ErrorCode.ERR_RoomIdNotFound; reply(response); return; } if (mapUnit.Room.Type != RoomType.Team) { response.Error = ErrorCode.ERR_RoonTypeError; reply(response); return; } var roomTeamComponent = mapUnit.Room.GetComponent <RoomTeamComponent>(); if (roomTeamComponent == null) { response.Error = ErrorCode.ERR_RoomTeamComponentNull; reply(response); return; } if (roomTeamComponent.Data?.LeaderUid != mapUnit.Uid) { response.Error = ErrorCode.ERR_RoomTeamIsNotLeader; reply(response); return; } if (mapUnit.Room.State != RoomState.Start) { response.Error = ErrorCode.ERR_RoomTeamStateCanNotToRun; reply(response); return; } // 判斷是否所有成員都已準備 bool haveNotReady = false; for (int i = 0; i < roomTeamComponent.MemberDatas.Length; i++) { if (roomTeamComponent.MemberDatas[i] != null && roomTeamComponent.MemberDatas[i].Uid != mapUnit.Uid && !roomTeamComponent.MemberDatas[i].IsReady) { haveNotReady = true; break; } } if (haveNotReady) { response.Error = ErrorCode.ERR_RoomTeamHaveNotReady; reply(response); return; } // 開始比賽 roomTeamComponent.TeamLeaderRun(); await Game.Scene.GetComponent <RoomComponent>().Update(mapUnit.Room); response.Error = ErrorCode.ERR_Success; reply(response); // 紀錄所有MapUnit RepeatedField <MapUnitInfo> mapUnitInfos = new RepeatedField <MapUnitInfo>(); List <MapUnit> mapUnits = mapUnit.Room.GetAll(); for (int i = 0; i < mapUnits.Count; i++) { // PathId 入場時決定 mapUnits[i].Info.PathId = i % 4; mapUnits[i].Info.DistanceTravelled = 0; mapUnitInfos.Add(mapUnits[i].Info); } // 廣播給本隊全體 ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>(); for (int i = 0; i < mapUnits.Count; i++) { if (mapUnits[i].MapUnitType == MapUnitType.Npc) { continue; } if (mapUnits[i].GetComponent <MapUnitGateComponent>().IsDisconnect) { continue; } M2C_TeamGoBattle m2c_TeamGoBattle = new M2C_TeamGoBattle(); m2c_TeamGoBattle.MapUnitInfos = mapUnitInfos; m2c_TeamGoBattle.MapUnitId = mapUnits[i].Id; ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(mapUnits[i].GetComponent <MapUnitGateComponent>().GateSessionActorId); actorMessageSender.Send(m2c_TeamGoBattle); } } catch (Exception e) { ReplyError(response, e, reply); } }
public async ETVoid DispatchAsync(Session session, ushort opcode, object message) { // 根据消息接口判断是不是Actor消息,不同的接口做不同的处理 switch (message) { case IFrameMessage iFrameMessage: // 如果是帧消息,构造成OneFrameMessage发给对应的unit { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId); // 这里设置了帧消息的id,防止客户端伪造 iFrameMessage.Id = unitId; OneFrameMessage oneFrameMessage = new OneFrameMessage { Op = opcode, AMessage = ByteString.CopyFrom(session.Network.MessagePacker.SerializeTo(iFrameMessage)) }; //actorLocationSender.Send(oneFrameMessage); Game.Scene.GetComponent <ServerFrameComponent>().Add(oneFrameMessage); return; } case IActorLocationRequest actorLocationRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId); int rpcId = actorLocationRequest.RpcId; // 这里要保存客户端的rpcId long instanceId = session.InstanceId; IResponse response = await actorLocationSender.Call(actorLocationRequest); response.RpcId = rpcId; // session可能已经断开了,所以这里需要判断 if (session.InstanceId == instanceId) { session.Reply(response); } break; } case IActorLocationMessage actorLocationMessage: { long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId; ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId); actorLocationSender.Send(actorLocationMessage); break; } case IActorRequest iActorRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long actorId = session.GetComponent <SessionUserComponent>().User.ActorID; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(actorId); int rpcId = iActorRequest.RpcId; // 这里要保存客户端的rpcId IResponse response = await actorMessageSender.Call(iActorRequest); response.RpcId = rpcId; session.Reply(response); return; } case IActorMessage iActorMessage: // gate session收到actor消息直接转发给actor自己去处理 { long actorId = session.GetComponent <SessionUserComponent>().User.ActorID; ActorMessageSender actorMessageSender = Game.Scene.GetComponent <ActorMessageSenderComponent>().Get(actorId); actorMessageSender.Send(iActorMessage); return; } default: { // 非Actor消息 Game.Scene.GetComponent <MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message)); break; } } }