Esempio n. 1
0
        /// <summary>
        ///
        /// </summary>
        private void Setup()
        {
            var builder = new ContainerBuilder();

            #region 通信相关组件

            builder.Register(c => this).As <IMessageSender>().SingleInstance();
            ////注册内置命令
            //RegisterActions(typeof(ActorService<TActorService>).Assembly.GetTypes());
            ////注册外置命令
            //RegisterActions(GetActions());

            //注册命令
            RegisterActions(DistrictContainer.GetApiAssemblyList());

            builder.Register(c => Actions)
            .As <IDictionary <string, IAction> >()
            .SingleInstance();

            //数据格式
            foreach (var responseConvert in typeof(IResponseConvert).Assembly.GetTypes().Where(item => typeof(IResponseConvert).IsAssignableFrom(item)))
            {
                if (responseConvert.IsInterface)
                {
                    continue;
                }

                var attrs = responseConvert.GetCustomAttributes(typeof(DisplayColumnAttribute), false);
                if (attrs.Any())
                {
                    var convertName = ((DisplayColumnAttribute)attrs[0]).DisplayColumn;
                    if (!string.IsNullOrEmpty(convertName))
                    {
                        builder.Register(c => Activator.CreateInstance(responseConvert))
                        .Keyed <IResponseConvert>(convertName.ToLower())
                        .SingleInstance();
                    }
                }
            }

            #endregion
            // 游戏容器
            DistrictContainer.InitContainers(builder);
            #region 通信框架初始化

            if (DistrictContainer.ServerIoc.IsRegistered <IProtoService>())
            {
                var list = new List <Assembly>();
                list.AddRange(DistrictContainer.GetServiceAssemblyList());
                list.AddRange(DistrictContainer.GetEntityAssemblyList());
                list.AddRange(DistrictContainer.GetApiAssemblyList());
                DistrictContainer.ServerIoc.Resolve <IProtoService>()
                .Init(list);
            }

            RedisDataBaseExtension.RedisSerilazer = DistrictContainer.ServerIoc.Resolve <IRedisSerializer>();
            if (Logger.IsTraceEnabled)
            {
                Logger.Trace($"Set RedisDataBaseExtension.RedisSerilazer = {RedisDataBaseExtension.RedisSerilazer.GetType().FullName}");
            }

            ProtocolPackage = DistrictContainer.ServerIoc.Resolve <IProtocolPackage>();
            if (Logger.IsTraceEnabled)
            {
                Logger.Trace($"Set ProtocolPackage = {ProtocolPackage.GetType().FullName}");
            }
            #endregion

            if (Logger.IsTraceEnabled)
            {
                Logger.Trace(@"
.______    __  .______          ___   .___________. __________   ___ 
|   _  \  |  | |   _  \        /   \  |           ||   ____\  \ /  / 
|  |_)  | |  | |  |_)  |      /  ^  \ `---|  |----`|  |__   \     /  
|   ___/  |  | |      /      /  /_\  \    |  |     |   __|   >   <   
|  |      |  | |  |\  \----./  _____  \   |  |     |  |____ /  .  \  
| _|      |__| | _| `._____/__/     \__\  |__|     |_______/__/ \__\ 
");
            }
        }
Esempio n. 2
0
        public byte[] OnReceive(ActorContext context)
        {
            if (context.Action == 0)
            {
                Logger.Debug("ping");

                var onlinecount = 0;
                if (context.ServerItmes.ContainsKey("OnlineCount"))
                {
                    onlinecount = Convert.ToInt32(context.ServerItmes["OnlineCount"]);
                }

                Ping(context.ServerName, onlinecount);
                return(null);
            }
            else if (context.Action == 2)//断线
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Session[{context.SessionId}] Logout ~");
                }

                var session = DistrictContainer.OnlineManager.GetSession(context.SessionId);
                if (session != null)
                {
                    DistrictContainer.OnlineManager.Logout(session.Id);
                    OnSessionClosed(session);
                }

                return(null);
            }

            var token = GetToken(context.Request.Token);

            context.Token = token;

            if (Logger.IsDebugEnabled)
            {
                Logger.Debug($"C2S Headers #{context.Token.Rid}# #{context.RemoteIp}# {context.Request.Headers}");
                Logger.Debug($"C2S Query #{context.Token.Rid}# #{context.RemoteIp}# {context.Request.QueryString}");
            }

            //授权检查
            if (!VerifyToken(DistrictContainer.GetDistrictConfig(token.Did), token))
            {
                throw new PirateXException("AuthError", "授权失败")
                      {
                          Code = StatusCode.Unauthorized
                      }
            }
            ;

            var format = context.Request.Headers["format"];

            if (!string.IsNullOrEmpty(format))
            {
                context.ResponseCovnert = format;
            }
            else
            {
                context.ResponseCovnert = DefaultResponseCovnert;
            }

            var lang = context.Request.Headers["lang"];

            if (!string.IsNullOrEmpty(lang))
            {
                Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
            }

            //request timeout
            //if ((DateTime.UtcNow.GetTimestamp() - context.Request.Timestamp) > 1000 * 60 * 2)
            //{
            //    Logger.Warn($"C2S Timeout t #{context.SessionId}# #{context.RemoteIp}# {context.Request.Headers} ");
            //    return;
            //}

            if (context.Request.O <= context.LastNo)
            {
                Logger.Warn($"C2S Timeout o #{context.SessionId}# #{context.RemoteIp}# {context.Request.Headers} ");
                return(null);
            }

            //执行动作
            var actionname = context.Request.C;

            using (var action = GetActionInstanceByName(actionname))
            {
                if (action != null)
                {
                    try
                    {
                        if (Equals(actionname, "NewSeed"))
                        {
                            OnSessionConnected(ToSession(context, context.Token));
                        }
                        else
                        {
                            //session = OnlineManager.GetSession(token.Rid);
                            var container = DistrictContainer.GetDistrictContainer(token.Did);
                            action.Resolver = container ?? throw new PirateXException("ContainerNull", "容器未定义")
                                                    {
                                                        Code = StatusCode.ContainerNull
                                                    };                                                                                               //.BeginLifetimeScope();
                        }

                        action.ServerReslover = DistrictContainer.ServerIoc;
                        action.Context        = context;
                        action.Logger         = Logger;
                        action.MessageSender  = this;

                        action.Execute();

                        if (Equals(actionname, "NewSeed"))
                        {
                            //session 保存
                            DistrictContainer.OnlineManager.Login(ToSession(context, context.Token));
                        }

                        var result = action.ResponseData;
                        if (result == null)
                        {
                            return(this.SendMessage(context, string.Empty));
                        }
                        return(result);
                    }
                    catch (Exception exception)
                    {
                        return(HandleException(context, exception));
                    }
                }
            }

            var headers = new NameValueCollection()
            {
                { "c", context.Request.C },
                { "i", MessageType.Boradcast },
                { "o", Convert.ToString(context.Request.O) },
                { "code", Convert.ToString((int)StatusCode.NotFound) },
                { "errorCode", "NotFound" },
                { "errorMsg", $"Action {actionname} not found!" }
            };

            //返回类型

            return(SendMessage <string>(context, headers, null));
        }