public static async ETTask LockEvent(this LocationProxyComponent self, long id, long key, long timeout = 60000)
        {
            Session       session  = Game.Scene.GetComponent <NetInnerComponent>().Get(self.LocationAddress);
            L2S_LockEvent response = (L2S_LockEvent)await session.Call(new S2L_LockEvent()
            {
                Id = id, Key = key, Timeout = timeout
            });

            if (response.Error != ErrorCode.ERR_Success)
            {
                if (!self.lockDict.TryGetValue(key, out var dict))
                {
                    dict = new Dictionary <long, ETTaskCompletionSource>();
                    self.lockDict.Add(key, dict);
                }
                var tcs = new ETTaskCompletionSource();
                dict.Add(id, tcs);
                await tcs.Task;
            }
        }
예제 #2
0
        public static async Task <bool> RegisterServer(this LocationProxyComponent self)
        {
            var success = false;

            for (int i = 0; i < 10; i++)
            {
                Session     session     = Game.Scene.GetComponent <NetInnerComponent>().Get(self.LocationAddress);
                StartConfig startConfig = Game.Scene.GetComponent <StartConfigComponent>().StartConfig;
                ServerInfo  info        = new ServerInfo();
                var         innerConfig = startConfig.GetComponent <InnerConfig>();
                info.NetInnerIp   = innerConfig.Host;
                info.NetInnerPort = innerConfig.Port;
                info.ServerId     = startConfig.AppId;
                info.ServerType   = (int)startConfig.AppType;
                Log.Debug("开始发送:" + info);
                var a = (ResponseMessage)await session.Call(new S2L_RegisterServer()
                {
                    Info = info
                });

                if (a.Tag != 0)
                {
                    Log.Fatal("连接本地服务器失败" + a);
                }
                else
                {
                    success = true;
                    break;
                }
                Thread.Sleep(1000);
            }
            if (success)
            {
                return(true);
            }
            else
            {
                Environment.Exit(0);  //0代表正常退出,非0代表某种错误的退出
            }
            return(true);
        }
        protected override async ETTask Run(Session session, C2G_EnterMap request, G2C_EnterMap response, Action reply)
        {
            //获取Player对象引用
            Player player = session.GetComponent <SessionPlayerComponent>().Player;

            // 在map服务器上创建战斗Unit
            IPEndPoint mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent <InnerConfig>().IPEndPoint;
            Session    mapSession = Game.Scene.GetComponent <NetInnerComponent>().Get(mapAddress);

            //由gate服务器向map服务器发送创建战斗单位请求,这里的id是数据库里玩家账号id
            M2G_CreateUnit createUnit =
                (M2G_CreateUnit)await mapSession.Call(new G2M_CreateUnit()
            {
                PlayerId = player.PlayerIdInDB, GateSessionId = session.Id
            });

            player.UnitId   = createUnit.UnitId;
            response.UnitId = createUnit.UnitId;

            reply();
        }
예제 #4
0
        //不懂TODO
        public static async ETVoid OnTestCall()
        {
            try
            {
                // 创建一个ETModel层的Session
                ETModel.Session session = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);

                // 创建一个ETHotfix层的Session, ETHotfix的Session会通过ETModel层的Session发送消息
                Session      realmSession = ComponentFactory.Create <Session, ETModel.Session>(session);
                R2C_TestCall r2CTestCall  = (R2C_TestCall)await realmSession.Call(new C2R_TestCall());

                realmSession.Dispose();

                //处理回调
                Log.Debug($"Error={r2CTestCall.Error},消息是={r2CTestCall.Message}");
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
예제 #5
0
        /// <summary>
        /// 登陆
        /// </summary>
        public static async ETVoid OnLoginAsync(string account, string password)
        {
            ETModel.Session session       = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);
            Session         realm_session = ComponentFactory.Create <Session, ETModel.Session>(session);
            //给登陆服务器发送登陆
            R2C_CowCowLogin r2cLogin = (R2C_CowCowLogin)await realm_session.Call(new C2R_CowCowLogin()
            {
                Account = account, Password = password
            });

            realm_session.Dispose();
            //将与消息服务器的链接session加入到SessionComponent组件
            if (r2cLogin.Error == ErrorCode.ERR_LoginError)
            {
                Log.Debug($"登录错误:{r2cLogin.Message}");
                PopupsHelper.ShowPopups($"登录错误:{r2cLogin.Message}");
                return;
            }
            Log.Debug("地址" + r2cLogin.Address);
            await LoginAsync(r2cLogin.Address, r2cLogin.Key);
        }
        public static async ETTask <Room> CreateTeamRoom(this LobbyComponent self, int mapAppId, RoomInfo roomInfo, TeamRoomData teamRoomData)
        {
            // 等候房間創建完成,並且也同步Room到了Lobby
            Session        mapSession     = SessionHelper.GetMapSession(mapAppId);
            M2L_TeamCreate m2L_TeamCreate = (M2L_TeamCreate)await mapSession.Call(new L2M_TeamCreate
            {
                Info = roomInfo,
                Data = teamRoomData,
            });

            if (m2L_TeamCreate.Error != ErrorCode.ERR_Success)
            {
                return(null);
            }

            Room room = BsonSerializer.Deserialize <Room>(m2L_TeamCreate.Json);

            CacheExHelper.WriteInCache(room, out room);

            return(room);
        }
예제 #7
0
        protected override async void Run(Session session, C2R_Login message, Action <R2C_Login> reply)
        {
            R2C_Login response = new R2C_Login();

            try
            {
                string query = $"{"{"}'Account':'{message.Account}','Password':'******'{"}"}";
                Log.Info($"----{query}");
                List <AccountInfo> accounts = await Game.Scene.GetComponent <DBProxyComponent>().QueryJson <AccountInfo>(query);

                if (accounts.Count == 0)
                {
                    response.Error = ErrorCode.ERR_AccountOrPasswordError;
                    reply(response);
                    return;
                }

                // 随机分配一个Gate
                StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();
                //Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
                IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
                Session    gateSession  = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);

                // 向gate请求一个key,客户端可以拿着这个key连接gate
                G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
                {
                    Account = message.Account
                });

                string outerAddress = config.GetComponent <OuterConfig>().IPEndPoint2.ToString();

                response.Address = outerAddress;
                response.Key     = g2RGetLoginKey.Key;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #8
0
        protected override async void Run(Session session, C2R_Login message, Action <R2C_Login> reply)
        {
            R2C_Login response = new R2C_Login();

            try
            {
                Console.WriteLine("userLogin:"******"key:" + message.Password);

                /*
                 * 账户密码验证
                 */
                int result = Game.Scene.GetComponent <MySqlComponent>().CheckPassWord(message.Account, message.Password);
                if (result == ErrorCode.ERR_Success)
                {
                    // 随机分配一个Gate
                    StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();
                    //Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
                    IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
                    Console.WriteLine("userLogin:" + innerAddress);
                    Session gateSession = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);

                    // 向gate请求一个key,客户端可以拿着这个key连接gate
                    G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
                    {
                        Account = message.Account
                    });

                    string outerAddress = config.GetComponent <OuterConfig>().IPEndPoint2.ToString();

                    response.Address = outerAddress;
                    response.Key     = g2RGetLoginKey.Key;
                }
                response.Error = result;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #9
0
        public async void OnLogin()
        {
            try
            {
                IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);

                string text = this.account.GetComponent <InputField>().text;

                R2C_Login r2CLogin;
                using (Session session = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint))
                {
                    r2CLogin = (R2C_Login)await session.Call(new C2R_Login()
                    {
                        Account = text, Password = "******"
                    });
                }

                connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);
                Session gateSession = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                ETModel.Game.Scene.AddComponent <SessionComponent>().Session = gateSession;
                G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                {
                    Key = r2CLogin.Key
                });

                Log.Info("登陆gate成功!");

                // 创建Player
                Player          player          = ETModel.ComponentFactory.CreateWithId <Player>(g2CLoginGate.PlayerId);
                PlayerComponent playerComponent = ETModel.Game.Scene.GetComponent <PlayerComponent>();
                playerComponent.MyPlayer = player;

                Game.Scene.GetComponent <UIComponent>().Create(UIType.UILobby);
                Game.Scene.GetComponent <UIComponent>().Remove(UIType.UILogin);
            }
            catch (Exception e)
            {
                Log.Error(e.ToStr());
            }
        }
        /// <summary>
        /// 创建房间
        /// </summary>
        /// <param name="self"></param>
        public static async void CreateRoom(this MatchComponent self)
        {
            if (self.CreateRoomLock)
            {
                return;
            }

            //消息加锁,避免因为延迟重复发多次创建消息
            self.CreateRoomLock = true;

            //发送创建房间消息
            IPEndPoint           mapIPEndPoint = Game.Scene.GetComponent <AllotMapComponent>().GetAddress().GetComponent <InnerConfig>().IPEndPoint;
            Session              mapSession    = Game.Scene.GetComponent <NetInnerComponent>().Get(mapIPEndPoint);
            MP2MH_CreateRoom_Ack createRoomRE  = await mapSession.Call(new MH2MP_CreateRoom_Req()) as MP2MH_CreateRoom_Ack;

            Room room = ComponentFactory.CreateWithId <Room>(createRoomRE.RoomID);

            Game.Scene.GetComponent <MatchRoomComponent>().Add(room);

            //解锁
            self.CreateRoomLock = false;
        }
예제 #11
0
        private async ETVoid RunAsync(Session session, C2R_Login message, Action <R2C_Login> reply)
        {
            R2C_Login response = new R2C_Login();

            try
            {
                Account ret = await CheckAccount(message, response);

                if (ret == null)
                {
                    reply(response);

                    return;
                }

                // 随机分配一个Gate
                StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();
                Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
                IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
                Session    gateSession  = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);

                // 向gate请求一个key,客户端可以拿着这个key连接gate
                G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
                {
                    PhoneNum = ret.PhoneNum
                });

                string outerAddress = config.GetComponent <OuterConfig>().Address2;

                response.Address = outerAddress;
                response.Key     = g2RGetLoginKey.Key;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #12
0
        public static async ETTask Send(this BenchmarkComponent self, Session session, int j)
        {
            try
            {
                await session.Call(new C2R_Ping());

                ++self.k;

                if (self.k % 100000 != 0)
                {
                    return;
                }

                long time2 = TimeHelper.ClientNow();
                long time  = time2 - self.time1;
                self.time1 = time2;
                Log.Info($"Benchmark k: {self.k} 每10W次耗时: {time} ms {session.Network.Count}");
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
예제 #13
0
        /// <summary>
        /// 将已在线的玩家踢下线
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task KickOutPlayer(long userId)
        {
            //验证账号是否在线,在线则踢下线
            //Real服务器上需要有在线玩家管理组件

            int gateAppId = Game.Scene.GetComponent <OnlineComponent>().GetGateAppId(userId);

            if (gateAppId != 0) //如果玩家在线 则返回其所在的AppID
            {
                Log.Debug($"玩家{userId}已在线 将执行踢下线操作");
                //如果Realm在线就移除掉
                Game.Scene.GetComponent <OnlineComponent>().Remove(userId);
                //获取玩家所在Gate服务器的Session
                StartConfig userGateConfig     = Game.Scene.GetComponent <StartConfigComponent>().Get(gateAppId);
                IPEndPoint  userGateIPEndPoint = userGateConfig.GetComponent <InnerConfig>().IPEndPoint;
                Session     userGateSession    = Game.Scene.GetComponent <NetInnerComponent>().Get(userGateIPEndPoint);
                //通知Gate服务器移除指定User
                await userGateSession.Call(new A0007_KickOutPlayer_R2G()
                {
                    UserID = userId
                });
            }
        }
        protected override async 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>();
            ActorProxyComponent  actorProxyComponent = Game.Scene.GetComponent <ActorProxyComponent>();

            //正在匹配中发送玩家退出匹配请求
            if (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 = user.UserID
                });

                user.IsMatching = false;
            }

            //正在游戏中发送玩家退出房间请求
            if (user.ActorID != 0)
            {
                ActorProxy actorProxy = actorProxyComponent.Get(user.ActorID);
                await actorProxy.Call(new Actor_PlayerExitRoom_Req()
                {
                    UserID = user.UserID
                });

                user.ActorID = 0;
            }
        }
예제 #15
0
        private async ETVoid RunAsync(Session session, C2R_Login message, Action <R2C_Login> reply)
        {
            R2C_Login response = new R2C_Login();

            try
            {
                //if (message.Account != "abcdef" || message.Password != "111111")
                //{
                //	response.Error = ErrorCode.ERR_AccountOrPasswordError;
                //	reply(response);
                //	return;
                //}

                // 随机分配一个Gate
                StartConfig config = Game.Scene.GetComponent <RealmGateAddressComponent>().GetAddress();
                //Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
                IPEndPoint innerAddress = config.GetComponent <InnerConfig>().IPEndPoint;
                Session    gateSession  = Game.Scene.GetComponent <NetInnerComponent>().Get(innerAddress);
                Log.Warning("请求Key+ " + session.Id);
                // 向gate请求一个key,客户端可以拿着这个key连接gate
                G2R_GetLoginKey g2RGetLoginKey = (G2R_GetLoginKey)await gateSession.Call(new R2G_GetLoginKey()
                {
                    Account = message.Account
                });

                Log.Warning("返回Key+ " + session.Id);
                string outerAddress = config.GetComponent <OuterConfig>().Address2;

                response.Address = outerAddress;
                response.Key     = g2RGetLoginKey.Key;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #16
0
        private async void RegisterAccount(string account, string code)
        {
            ETModel.Session session = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(GlobalConfigComponent.Instance.GlobalProto.Address);

            Session             realmSession = ComponentFactory.Create <Session, ETModel.Session>(session);
            G2C_MobileLogin_Res mobileLogin  = (G2C_MobileLogin_Res)await realmSession.Call(
                new C2G_MobileLogin_Req()
            {
                Mobile     = account,
                VerifyCode = code,
            });

            if (mobileLogin.Error != 0)
            {
                Game.PopupComponent.ShowMessageBox(mobileLogin.Message);
                return;
            }
            if (!PlayerPrefs.HasKey("Account01"))
            {
                PlayerPrefs.SetString("Account01", $"{mobileLogin.Account}-{mobileLogin.Token}");
            }
            else
            {
                if (!PlayerPrefs.HasKey("Account02"))
                {
                    PlayerPrefs.SetString("Account02", $"{mobileLogin.Account}-{mobileLogin.Token}");
                }
                else
                {
                    if (!PlayerPrefs.HasKey("Account03"))
                    {
                        PlayerPrefs.SetString("Account03", $"{mobileLogin.Account}-{mobileLogin.Token}");
                    }
                }
            }
            LoginRequest(mobileLogin.Account, mobileLogin.Token);
        }
예제 #17
0
        private async void OnClickPressTest()
        {
            Session sessionWrap = null;

            try
            {
                //IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);
                IPEndPoint      connetEndPoint = NetworkHelper.ToIPEndPoint("10.224.4.158:10006");
                ETModel.Session session        = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);

                sessionWrap = ComponentFactory.Create <Session, ETModel.Session>(session);

                G2C_PressTest g2C_PressTest = (G2C_PressTest)await sessionWrap.Call(new C2G_PressTest());

                UINetLoadingComponent.closeNetLoading();

                sessionWrap.Dispose();
            }
            catch (Exception e)
            {
                sessionWrap?.Dispose();
                Log.Error(e);
            }
        }
예제 #18
0
        protected async ETVoid RunAsync(Session session, C2G_EnterOutSpace message, Action <G2C_EnterOutSpace> reply)
        {
            G2C_EnterOutSpace response = new G2C_EnterOutSpace();

            try
            {            //NOTE 进入地图后第一个调用
                Player player = session.GetComponent <SessionPlayerComponent>().Player;
                // 在map服务器上创建战斗Unit
                IPEndPoint     mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent <InnerConfig>().IPEndPoint;           //取得战斗服地址
                Session        mapSession = Game.Scene.GetComponent <NetInnerComponent>().Get(mapAddress);
                M2G_CreateShip createUnit = (M2G_CreateShip)await mapSession.Call(new G2M_CreateShip()
                {
                    PlayerId = player.Id, GateSessionId = session.InstanceId
                });                                                                                                                                                  //向战斗服创建unit

                player.ShipId   = createUnit.ShipId;
                response.ShipId = createUnit.ShipId;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #19
0
        public async ETVoid Awake()
        {
            TimerComponent tiemr   = ETModel.Game.Scene.GetComponent <TimerComponent>();
            Session        session = this.GetParent <Session>();

            this.isStart = true;
            int connectCount = 0;

            while (isStart)
            {
                try
                {
                    //服务器太久没有接收到心跳,会踢掉客户端
                    _sendTimer = TimeHelper.ClientNowSeconds();
                    await session.Call(_request);

                    _receviceTimer = TimeHelper.ClientNowSeconds();
                    long time = (_receviceTimer - _sendTimer) / 2;
                    ping = time < 0 ? -1 : time;
                    if (ping == -1)
                    {
                        this.ReConnect(connectCount < 2);
                        connectCount++;
                        Log.Debug("Ping断线了");
                    }
                }
                catch (Exception e)
                {
                    //重连两次,或者弹窗跳到登录框界面
                    this.ReConnect(connectCount < 2);
                    connectCount++;
                    Log.Debug($"Ping异常(在这里重连):{e.Message}");
                }
                await tiemr.WaitAsync(interval);
            }
        }
예제 #20
0
        private static async void RequestLock(this LockComponent self)
        {
            try
            {
                Session         session       = Game.Scene.GetComponent <NetInnerComponent>().Get(self.address);
                string          serverAddress = StartConfigComponent.Instance.StartConfig.ServerIP;
                G2G_LockRequest request       = new G2G_LockRequest {
                    Id = self.Entity.Id, Address = serverAddress
                };
                await session.Call(request);

                self.status = LockStatus.Locked;

                foreach (ETTaskCompletionSource <bool> taskCompletionSource in self.queue)
                {
                    taskCompletionSource.SetResult(true);
                }
                self.queue.Clear();
            }
            catch (Exception e)
            {
                Log.Error($"获取锁失败: {self.address} {self.Entity.Id} {e}");
            }
        }
        protected async ETVoid RunAsync(Session session, C2G_EnterMap message, Action <G2C_EnterMap> reply)
        {
            G2C_EnterMap response = new G2C_EnterMap();

            try
            {
                Player player = session.GetComponent <SessionPlayerComponent>().Player;
                // 在map服务器上创建战斗Unit
                IPEndPoint     mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent <InnerConfig>().IPEndPoint;
                Session        mapSession = Game.Scene.GetComponent <NetInnerComponent>().Get(mapAddress);
                M2G_CreateUnit createUnit = (M2G_CreateUnit)await mapSession.Call(new G2M_CreateUnit()
                {
                    PlayerId = player.Id, GateSessionId = session.InstanceId
                });

                player.UnitId   = createUnit.UnitId;
                response.UnitId = createUnit.UnitId;
                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #22
0
        public static async ETVoid OnLoginAsync(string account, string password)
        {
            try
            {
                // 显示加载UI
                ETModel.Game.EventSystem.Run(ETModel.EventIdType.ShowLoadingUI);
                // 如果正在登录,就驳回登录请求,为了双重保险,点下登录按钮后,收到服务端响应之前将不能再点击
                if (isLogining)
                {
                    FinalRun();
                    return;
                }

                isLogining = true;

                if (account == "" || password == "")
                {
                    Game.EventSystem.Run(EventIdType.ShowLoginInfo, "账号或密码不能为空");
                    FinalRun();
                    return;
                }

                // 创建一个ETModel层的Session
                ETModel.Session session = ETModel.Game.Scene.GetComponent <NetOuterComponent>()
                                          .Create(GlobalConfigComponent.Instance.GlobalProto.Address);
                // 创建一个ETHotfix层的Session, ETHotfix的Session会通过ETModel层的Session发送消息
                Session realmSession = ComponentFactory.Create <Session, ETModel.Session>(session);

                Game.EventSystem.Run(EventIdType.ShowLoginInfo, "登陆中。。。");
                // 发送登录请求,账号,密码均为传来的参数
                R2C_Login r2CLogin = (R2C_Login)await realmSession.Call(new C2R_Login()
                {
                    Account = account, Password = password
                });

                if (r2CLogin.Error == ErrorCode.ERR_LoginError)
                {
                    Game.EventSystem.Run(EventIdType.ShowLoginInfo, "登录失败,账号或密码错误");
                    FinalRun();
                    return;
                }

                //释放realmSession
                realmSession.Dispose();

                // 创建一个ETModel层的Session,并且保存到ETModel.SessionComponent中
                ETModel.Session gateSession = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(r2CLogin.Address);
                ETModel.Game.Scene.AddComponent <ETModel.SessionComponent>().Session = gateSession;

                // 创建一个ETHotfix层的Session, 并且保存到ETHotfix.SessionComponent中
                Game.Scene.AddComponent <SessionComponent>().Session = ComponentFactory.Create <Session, ETModel.Session>(gateSession);

                // 增加客户端断线处理组件
                Game.Scene.GetComponent <SessionComponent>().Session.AddComponent <SessionOfflineComponent>();

                // 增加心跳组件
                ETModel.Game.Scene.GetComponent <ETModel.SessionComponent>().Session.AddComponent <HeartBeatComponent>();

                await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                {
                    Key = r2CLogin.Key
                });

                Game.EventSystem.Run(EventIdType.ShowLoginInfo, "登录成功");

                // 创建Player(抽象化的玩家),这里的id是数据库里的账号id
                Player          player          = ETModel.ComponentFactory.CreateWithId <Player>(r2CLogin.PlayerId);
                PlayerComponent playerComponent = ETModel.Game.Scene.GetComponent <PlayerComponent>();
                playerComponent.MyPlayer = player;

                // 登录完成
                Game.EventSystem.Run(EventIdType.LoginFinish);

                // 测试消息有成员是class类型
                // G2C_PlayerInfo g2CPlayerInfo = (G2C_PlayerInfo) await SessionComponent.Instance.Session.Call(new C2G_PlayerInfo());
                // Debug.Log("测试玩家信息为" + g2CPlayerInfo.Message);
                FinalRun();
            }
            catch (Exception e)
            {
                Log.Error(e);
                FinalRun();
            }
        }
예제 #23
0
        public async void OnLogin()
        {
            try
            {
                //
                IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);


                // 创建一个ETModel层的Session
                ETModel.Session session      = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                Session         realmSession = ComponentFactory.Create <Session, ETModel.Session>(session);

                /*
                 * 请求登录
                 */
                R2C_Login r2CLogin = (R2C_Login)await realmSession.Call(new C2R_Login()
                {
                    Account  = this.account.GetComponent <InputField>().text,
                    Password = this.password.GetComponent <InputField>().text
                }
                                                                        );

                realmSession.Dispose();

                /*
                 * 处理登录结果
                 */
                if (r2CLogin.Error == ErrorCode.ERR_Success)
                {
                    connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);
                    // 创建一个ETModel层的Session,并且保存到ETModel.SessionComponent中"111.230.133.20:10002"
                    ETModel.Session gateSession = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                    ETModel.Game.Scene.AddComponent <ETModel.SessionComponent>().Session = gateSession;

                    // 创建一个ETHotfix层的Session, 并且保存到ETHotfix.SessionComponent中
                    Game.Scene.AddComponent <SessionComponent>().Session = ComponentFactory.Create <Session, ETModel.Session>(gateSession);

                    G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                    {
                        Key = r2CLogin.Key
                    });

                    Log.Info("登陆gate成功!");

                    // 创建Player
                    Player          player          = ETModel.ComponentFactory.CreateWithId <Player>(g2CLoginGate.PlayerId);
                    PlayerComponent playerComponent = ETModel.Game.Scene.GetComponent <PlayerComponent>();
                    playerComponent.MyPlayer = player;

                    Game.Scene.GetComponent <UIComponent>().Create(UIType.UILobby);
                    Game.Scene.GetComponent <UIComponent>().Remove(UIType.UILogin);
                }
                else if (r2CLogin.Error == ErrorCode.ERR_AccountInvaild)
                {
                    Game.Scene.GetComponent <UIAlertsGrayComponent>().CreateAlertWin("账号中有不法字符~", onAlertCbLoginFail, "好的~");
                }
                else if (r2CLogin.Error == ErrorCode.ERR_PasswordInvaild)
                {
                    Game.Scene.GetComponent <UIAlertsGrayComponent>().CreateAlertWin("密码中有不法字符~", onAlertCbLoginFail, "好的~");
                }
                else if (r2CLogin.Error == ErrorCode.ERR_PasswordIncorrect)
                {
                    Game.Scene.GetComponent <UIAlertsGrayComponent>().CreateAlertWin("密码不正确~", onAlertCbLoginFail, "好的~");
                }
                else if (r2CLogin.Error == ErrorCode.ERR_AccountNotExist)
                {
                    UIAlertsGrayComponent l = Game.Scene.GetComponent <UIAlertsGrayComponent>();
                    Game.Scene.GetComponent <UIAlertsGrayComponent>().CreateAlertWin("账号不存在~", onAlertCbLoginFail, "好的~");
                }
                else if (r2CLogin.Error == ErrorCode.ERR_DataBaseRead)
                {
                    Game.Scene.GetComponent <UIAlertsGrayComponent>().CreateAlertWin("网络异常~", onAlertCbLoginFail, "好的~");
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
예제 #24
0
        protected override async ETTask Run(Unit unit, Actor_TransferRequest message, Action <Actor_TransferResponse> reply)
        {
            Actor_TransferResponse response = new Actor_TransferResponse();

            try
            {
                long unitId = unit.Id;

                // 先在location锁住unit的地址
                await Game.Scene.GetComponent <LocationProxyComponent>().Lock(unitId, unit.InstanceId);

                // 删除unit,让其它进程发送过来的消息找不到actor,重发
                Game.EventSystem.Remove(unitId);

                long instanceId = unit.InstanceId;

                int mapIndex = message.MapIndex;

                StartConfigComponent startConfigComponent = StartConfigComponent.Instance;

                // 考虑AllServer情况
                if (startConfigComponent.Count == 1)
                {
                    mapIndex = 0;
                }

                // 传送到map
                StartConfig mapConfig = startConfigComponent.MapConfigs[mapIndex];
                IPEndPoint  address   = mapConfig.GetComponent <InnerConfig>().IPEndPoint;
                Session     session   = Game.Scene.GetComponent <NetInnerComponent>().Get(address);

                // 只删除不disponse否则M2M_TrasferUnitRequest无法序列化Unit
                Game.Scene.GetComponent <UnitComponent>().RemoveNoDispose(unitId);
                M2M_TrasferUnitResponse m2m_TrasferUnitResponse = (M2M_TrasferUnitResponse)await session.Call(new M2M_TrasferUnitRequest()
                {
                    Unit = unit
                });

                unit.Dispose();

                // 解锁unit的地址,并且更新unit的instanceId
                await Game.Scene.GetComponent <LocationProxyComponent>().UnLock(unitId, instanceId, m2m_TrasferUnitResponse.InstanceId);

                reply(response);
            }
            catch (Exception e)
            {
                ReplyError(response, e, reply);
            }
        }
예제 #25
0
 public static async ETVoid SaveLog(this DBProxyComponent self, ComponentWithId component)
 {
     Session session = Game.Scene.GetComponent <NetInnerComponent>().Get(self.dbAddress);
     await session.Call(new DBSaveRequest { Component = component, NeedCache = false, CollectionName = "Log" });
 }
예제 #26
0
 public static async ETTask Save(this DBProxyComponent self, ComponentWithId component, bool needCache, CancellationToken cancellationToken)
 {
     Session session = Game.Scene.GetComponent <NetInnerComponent>().Get(self.dbAddress);
     await session.Call(new DBSaveRequest { Component = component, NeedCache = needCache }, cancellationToken);
 }
예제 #27
0
 public static async ETTask SaveBatch(this DBProxyComponent self, List <ComponentWithId> components, bool needCache = true)
 {
     Session session = Game.Scene.GetComponent <NetInnerComponent>().Get(self.dbAddress);
     await session.Call(new DBSaveBatchRequest { Components = components, NeedCache = needCache });
 }
예제 #28
0
        public async Task OnThirdLogin(string third_id, string name, string head)
        {
            //加锁
            if (isLogining)
            {
                return;
            }
            isLogining = true;

            Session sessionWrap = null;

            try
            {
                UINetLoadingComponent.showNetLoading();

                // IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);
                IPEndPoint connetEndPoint = NetConfig.getInstance().ToIPEndPointWithYuMing();
#if Localhost
                connetEndPoint = NetworkHelper.ToIPEndPoint("10.224.5.74:10002");
#endif
                ETModel.Session session = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                sessionWrap = ComponentFactory.Create <Session, ETModel.Session>(session);

                name = name.Replace("'", "*");
                R2C_ThirdLogin r2CLogin = (R2C_ThirdLogin)await sessionWrap.Call(new C2R_ThirdLogin()
                {
                    Third_Id = third_id, MachineId = PlatformHelper.GetMacId(), ChannelName = PlatformHelper.GetChannelName(), ClientVersion = PlatformHelper.GetVersionName(), Name = name, Head = head
                });

                sessionWrap.Dispose();

                UINetLoadingComponent.closeNetLoading();

                if (r2CLogin.Error != ErrorCode.ERR_Success)
                {
                    ToastScript.createToast(r2CLogin.Message);
                    return;
                }

                UINetLoadingComponent.showNetLoading();

                // connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);
//                connetEndPoint = NetConfig.getInstance().ToIPEndPointWithYuMing();
                string[] temp = r2CLogin.Address.Split(':');
                connetEndPoint = ToIPEndPointWithYuMing(Convert.ToInt32(temp[1]));

                // connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);

#if Localhost
                connetEndPoint = NetworkHelper.ToIPEndPoint("10.224.5.74:10002");
#endif

                ETModel.Session gateSession = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                Game.Scene.GetComponent <SessionComponent>().Session = ComponentFactory.Create <Session, ETModel.Session>(session);
                ETModel.Game.Scene.GetComponent <ETModel.SessionComponent>().Session = gateSession;

                // Log.Info("gateSession:"+ connetEndPoint.ToString());
                G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                {
                    Key = r2CLogin.Key
                });

                ToastScript.createToast("登录成功");
                //挂心跳包
                Game.Scene.GetComponent <SessionComponent>().Session.AddComponent <HeartBeatComponent>();
                UINetLoadingComponent.closeNetLoading();

                await getAllData();

                isLoginSuccess = true;

                Game.Scene.GetComponent <PlayerInfoComponent>().uid = g2CLoginGate.Uid;

                PlayerInfoComponent.Instance.SetShopInfoList(g2CLoginGate.ShopInfoList);
                PlayerInfoComponent.Instance.SetBagInfoList(g2CLoginGate.BagList);
                PlayerInfoComponent.Instance.ownIcon = g2CLoginGate.ownIcon;

                Game.Scene.GetComponent <UIComponent>().Create(UIType.UIMain);
                Game.Scene.GetComponent <UIComponent>().Remove(UIType.UILogin);
                isLogining = false;
            }
            catch (Exception e)
            {
                sessionWrap?.Dispose();
                Log.Error("OnThirdLogin:" + e);
                isLogining = false;
            }
        }
예제 #29
0
        public async Task OnLoginPhone(string phone, string code, string token)
        {
            Session sessionWrap = null;

            try
            {
                UINetLoadingComponent.showNetLoading();

                //IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address);

                IPEndPoint      connetEndPoint = ToIPEndPointWithYuMing(NetConfig.getInstance().getServerPort());
                ETModel.Session session        = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                sessionWrap = ComponentFactory.Create <Session, ETModel.Session>(session);
                R2C_PhoneLogin r2CLogin = (R2C_PhoneLogin)await sessionWrap.Call(new C2R_PhoneLogin()
                {
                    Phone = phone, Code = code, Token = token, MachineId = PlatformHelper.GetMacId(), ChannelName = PlatformHelper.GetChannelName(), ClientVersion = PlatformHelper.GetVersionName()
                });

                //R2C_PhoneLogin r2CLogin = (R2C_PhoneLogin)await sessionWrap.Call(new C2R_PhoneLogin() { Phone = phone, Code = code, Token = token, MachineId = "1234", ChannelName = "jav", ClientVersion = "1.1.0" });
                sessionWrap.Dispose();

                UINetLoadingComponent.closeNetLoading();

                if (r2CLogin.Error != ErrorCode.ERR_Success)
                {
                    ToastScript.createToast(r2CLogin.Message);

                    if (r2CLogin.Error == ErrorCode.ERR_TokenError)
                    {
                        PlayerPrefs.SetString("Phone", "");
                        PlayerPrefs.SetString("Token", "");

                        panel_phoneLogin.transform.localScale = new Vector3(1, 1, 1);
                    }

                    if (r2CLogin.Message.CompareTo("用户不存在") == 0)
                    {
                        panel_phoneLogin.transform.localScale = new Vector3(1, 1, 1);
                    }

                    return;
                }

                UINetLoadingComponent.showNetLoading();


                //connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address);
                //connetEndPoint = NetConfig.getInstance().ToIPEndPointWithYuMing();
                string[] temp = r2CLogin.Address.Split(':');
                connetEndPoint = ToIPEndPointWithYuMing(Convert.ToInt32(temp[1]));
                ETModel.Session gateSession = ETModel.Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint);
                Game.Scene.GetComponent <SessionComponent>().Session = ComponentFactory.Create <Session, ETModel.Session>(session);
                ETModel.Game.Scene.GetComponent <ETModel.SessionComponent>().Session = gateSession;

                G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate()
                {
                    Key = r2CLogin.Key
                });

                UINetLoadingComponent.closeNetLoading();

                ToastScript.createToast("登录成功");
                //挂心跳包
                Game.Scene.GetComponent <SessionComponent>().Session.AddComponent <HeartBeatComponent>();
                UINetLoadingComponent.closeNetLoading();
                await getAllData();

                isLoginSuccess = true;

                {
                    // 保存Phone
                    PlayerPrefs.SetString("Phone", phone);

                    // 保存Token
                    PlayerPrefs.SetString("Token", r2CLogin.Token);
                }

                Game.Scene.GetComponent <PlayerInfoComponent>().uid = g2CLoginGate.Uid;

                PlayerInfoComponent.Instance.SetShopInfoList(g2CLoginGate.ShopInfoList);
                PlayerInfoComponent.Instance.SetBagInfoList(g2CLoginGate.BagList);
                PlayerInfoComponent.Instance.ownIcon = g2CLoginGate.ownIcon;

                ResourcesComponent resourcesComponent = ETModel.Game.Scene.GetComponent <ResourcesComponent>();
                await resourcesComponent.LoadBundleAsync($"UIMain.unity3d");

                await resourcesComponent.LoadBundleAsync($"Image_Main.unity3d");

                Game.Scene.GetComponent <UIComponent>().Create(UIType.UIMain);
                Game.Scene.GetComponent <UIComponent>().Remove(UIType.UILogin);
            }
            catch (Exception e)
            {
                sessionWrap?.Dispose();
                Log.Error(e);
            }
        }
        public static async ETTask <List <long> > GetAllIds(this CacheProxyComponent self, string collectionName)
        {
            Session session = Game.Scene.GetComponent <NetInnerComponent>().Get(self.dbAddress);
            CacheGetAllIdsResponse cacheDeleteResponse = (CacheGetAllIdsResponse)await session.Call(new CacheGetAllIdsRequest
                                                                                                    { CollectionName = collectionName });

            return(cacheDeleteResponse.IdList);
        }