private static BaseCommand CreateCommand(string cmd, string assemblyName) { string typeName = ""; var arr = cmd.Split(':'); string tempcmd = arr.Length > 1 ? arr[1] : arr[0]; if (ZyGameBaseConfigManager.GameSetting.HasSetting) { typeName = ZyGameBaseConfigManager.GameSetting.GetGmCommandType(cmd); typeName = !string.IsNullOrEmpty(typeName) ? typeName : tempcmd + "Command"; } else { CommandCollection cmdList = ((GmSection)ConfigurationManager.GetSection(SectionName)).Command; CommandElement cmdElement = cmdList[cmd]; typeName = cmdElement != null ? cmdElement.TypeName : tempcmd + "Command"; } string commandType = typeName; if (typeName.IndexOf(",") == -1) { commandType = string.Format("{0}.{1},{0}", assemblyName, typeName); } var type = Type.GetType(commandType, false, true); if (type != null) { return(type.CreateInstance <BaseCommand>()); } return(ScriptEngines.ExecuteCSharp(string.Format("{0}.{1}", assemblyName, typeName))); }
private static async Task RunAsync(string[] args) { try { if (ScriptEngines.RunMainProgram(args)) { TraceLog.WriteLine("{0} Server has started successfully!", DateTime.Now.ToString("HH:mm:ss")); TraceLog.WriteLine("# Server is listening..."); } else { TraceLog.WriteLine("{0} Server failed to start!", DateTime.Now.ToString("HH:mm:ss")); } } catch (Exception ex) { TraceLog.WriteLine("{0} Server failed to start error:{1}", DateTime.Now.ToString("HH:mm:ss"), ex.Message); TraceLog.WriteError("RunMain error:{0}", ex); } while (!GameEnvironment.IsCanceled) { await Task.Delay(1000); } OnStop(); }
public static CaseStep Create(string formatType, string stepName, int index) { string typeName = string.Format(formatType, stepName); string code = string.Format(ConfigUtils.GetSetting("CaseStep.Script.Format", "Case.Step{0}.cs"), stepName); var instance = ScriptEngines.Execute(code, typeName); //var instance = type.CreateInstance<CaseStep>(); if (instance == null) { throw new NullReferenceException(string.Format("Get CaseStep object is null, type:{1}, script code:{0}", code, typeName)); } instance.Action = stepName; instance.netWriter = new NetWriter(); instance.netReader = new NetReader(new CustomHeadFormater()); instance.indentify = index; if (instance.isCustom) { GameRanking.Pack.MessagePack headPack = new GameRanking.Pack.MessagePack() { MsgId = 1, ActionId = int.Parse(stepName), SessionId = "", UserId = 0 }; byte[] header = ProtoBufUtils.Serialize(headPack); instance.netWriter.SetHeadBuffer(header); instance.netWriter.SetBodyData(null); } return(instance); }
/// <summary> /// Inits the task. /// </summary> /// <returns><c>true</c>, if task was inited, <c>false</c> otherwise.</returns> protected bool InitTask() { TNet.Cache.Generic.CacheList <string> st; _taskScope = ScriptEngines.Execute("Lib.Task", null); return(_taskScope != null); }
internal static BaseStruct FindScriptRoute(ActionGetter actionGetter, int actionID) { string scriptTypeName = string.Format(GameEnvironment.Setting.ScriptTypeName, actionID); string scriptCode = ""; if (!ScriptEngines.SettupInfo.DisablePython) //By Seamoon 在Python禁用的情况下,就没有必要再加载了 { scriptCode = string.Format("action.action{0}", actionID); dynamic scriptScope = ScriptEngines.ExecutePython(scriptCode); if (scriptScope != null) { bool ignoreAuthorize = _ignoreAuthorizeSet.Contains(actionID); return(new ScriptAction(ScriptType.Python, actionID, actionGetter, scriptScope, ignoreAuthorize)); } } if (!ScriptEngines.SettupInfo.DisableLua) { scriptCode = string.Format("Action{0}", actionID); dynamic scriptScope = ScriptEngines.ExecuteLua("GetTable", scriptCode, actionID); if (scriptScope != null) { bool ignoreAuthorize = _ignoreAuthorizeSet.Contains(actionID); return(new LuaAction(actionID, actionGetter, scriptScope, ignoreAuthorize)); } } scriptCode = string.Format("action.action{0}", actionID); BaseStruct baseStruct = ScriptEngines.Execute(scriptCode, scriptTypeName, actionGetter); if (baseStruct != null) { return(baseStruct); } return(null); }
/// <summary> /// Set language object. /// </summary> private static void SetLang(string typeName) { if (string.IsNullOrEmpty(typeName)) { typeName = ConfigManager.Configger.GetFirstOrAddConfig <AppServerSection>().LanguageTypeName; } var obj = ScriptEngines.Execute(null, typeName); if (obj != null) { _instance = obj; return; } //get default lang typeName = ConfigManager.Configger.GetFirstOrAddConfig <AppServerSection>().LanguageTypeName; var type = Type.GetType(typeName, false, false); if (type != null) { _instance = type.CreateInstance(); } else { TraceLog.WriteWarn("Can not find the corresponding language configuration,typeName:{0}", typeName);//By Seamoon } }
protected override void OnStartAffer() { try { var setting = new EnvironmentSetting(); setting.EntityAssembly = Assembly.Load("GameRanking.Model"); ScriptEngines.AddReferencedAssembly("GameRanking.Model.dll"); ActionFactory.SetActionIgnoreAuthorize(1000, 1001); var cacheSetting = new CacheSetting(); cacheSetting.ChangedHandle += OnChangedNotify; GameEnvironment.Start(setting, cacheSetting); var cache = new ShareCacheStruct <UserRanking>(); Stopwatch t = new Stopwatch(); t.Start(); var list = cache.FindAll(false); t.Stop(); if (list.Count > 0) { } Console.WriteLine("The server is staring..."); } catch (Exception ex) { TraceLog.WriteError("App star error:{0}", ex); } }
protected void Application_Start(object sender, EventArgs e) { try { var setting = new EnvironmentSetting(); setting.ClientDesDeKey = "j6=9=1ac"; setting.EntityAssembly = Assembly.Load("ZyGames.Tianjiexing.Model"); ScriptEngines.AddReferencedAssembly(new string[] { "ZyGames.Tianjiexing.Lang.dll", "ZyGames.Tianjiexing.Model.dll", "ZyGames.Tianjiexing.Component.dll", "ZyGames.Tianjiexing.BLL.Combat.dll", "ZyGames.Tianjiexing.BLL.GM.dll", "ZyGames.Tianjiexing.BLL.dll" }); GameEnvironment.Start(setting); SystemGlobal.Run(); #if (DEBUG) TraceLog.WriteError("系统正使用Debug版本"); #else TraceLog.ReleaseWrite("系统正使用Release版本"); #endif } catch (Exception ex) { TraceLog.WriteError("global start error:{0}", ex); } }
protected override void OnStartAffer() { try { var setting = new EnvironmentSetting(); setting.ClientDesDeKey = "j6=9=1ac"; setting.EntityAssembly = Assembly.Load("ZyGames.Doudizhu.Model"); GameEnvironment.Start(setting); ScriptEngines.AddReferencedAssembly(new string[] { "ZyGames.Doudizhu.Lang.dll", "ZyGames.Doudizhu.Model.dll", "ZyGames.Doudizhu.Bll.dll" }); ActionFactory.SetActionIgnoreAuthorize(1012, 9001, 9203); AppstoreClientManager.Current.InitConfig(); LoadUnlineUser(); InitRanking(); } catch (Exception ex) { TraceLog.WriteError("OnStartAffer error:{0}", ex); } }
protected override void Dispose(bool disposing) { if (!IsDisposed) { scriptEngines = null; } }
/// <summary> /// /// </summary> /// <returns></returns> protected virtual async System.Threading.Tasks.Task RunAsync() { try { if (ScriptEngines.RunMainProgram()) { TraceLog.WriteLine("{0} Server has started successfully!", DateTime.Now.ToString("HH:mm:ss")); TraceLog.WriteLine("# Server is listening..."); } else { TraceLog.WriteLine("{0} Server failed to start!", DateTime.Now.ToString("HH:mm:ss")); } } catch (Exception ex) { TraceLog.WriteLine("{0} Server failed to start error:{1}", DateTime.Now.ToString("HH:mm:ss"), ex.Message); TraceLog.WriteError("RunMain error:{0}", ex); } finally { TraceLog.WriteLine("# Server exit command \"Ctrl+C\" or \"Ctrl+Break\"."); } await RunWait(); }
static void Main(string[] args) { try { ConsoleColor currentForeColor = Console.ForegroundColor; var setting = new EnvironmentSetting(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(string.Format(CharFormat, Assembly.GetExecutingAssembly().GetName().Version, setting.ProductCode, setting.ProductServerId, setting.GamePort)); GameEnvironment.Start(setting); Console.ForegroundColor = currentForeColor; if (ScriptEngines.RunMainProgram(args)) { Console.WriteLine("{0} Server has started successfully!", DateTime.Now.ToString("HH:mm:ss")); Console.WriteLine("# Server is listening..."); } else { Console.WriteLine("{0} Server failed to start!", DateTime.Now.ToString("HH:mm:ss")); } Console.ReadKey(); ScriptEngines.StopMainProgram(); } catch (Exception ex) { Console.WriteLine("{0} Server failed to start!", DateTime.Now.ToString("HH:mm:ss")); TraceLog.WriteError("Server failed to start error:{0}", ex); Console.ReadKey(); } }
internal static BaseStruct FindScriptRoute(HttpGet httpGet, int actionID) { string scriptTypeName = string.Format(GameEnvironment.Setting.ScriptTypeName, actionID); string scriptCode = ""; if (!ScriptEngines.DisablePython) //By Seamoon 在Python禁用的情况下,就没有必要再加载了 { scriptCode = string.Format("{0}/action/action{1}.py", ScriptEngines.PythonDirName, actionID); dynamic scriptScope = ScriptEngines.Execute(scriptCode, null); if (scriptScope != null) { bool ignoreAuthorize = _ignoreAuthorizeSet.Contains(actionID); return(new ScriptAction((short)actionID, httpGet, scriptScope, ignoreAuthorize)); } } scriptCode = string.Format("{0}/action/action{1}.cs", ScriptEngines.CSharpDirName, actionID); BaseStruct baseStruct = ScriptEngines.Execute(scriptCode, scriptTypeName, httpGet); if (baseStruct != null) { return(baseStruct); } return(null); }
public override bool TakeAction() { switch (m_RequestPacket.Type) { case 1: DataTableLoader.LoadDataTables("Lobby"); m_ResponsePacket.Success = true; break; case 2: FlushKey(m_RequestPacket.Params); break; case 3: GameConfigs.Reload(); m_ResponsePacket.Success = true; break; case 4: GetOnlinePlayerCount(); break; case 5: ScriptEngines.Initialize(); break; default: return(false); } return(true); }
private static string GetEntityTypeFromKey(string key, out string typeName, ref Type type, out string asmName, out bool isEntityType, out string redisKey) { int index = key.IndexOf(','); var arr = (index > -1 ? key.Substring(0, index) : key).Split('_'); typeName = arr[0]; asmName = index == -1 ? "" : key.Substring(index + 1, key.Length - index - 1); string persionKey = string.Empty; string entityKey = string.Empty; if (arr.Length > 1) { entityKey = arr[1]; var tempArr = entityKey.Split('|'); if (tempArr.Length > 1) { persionKey = tempArr[0]; entityKey = tempArr[1]; } } isEntityType = false; if (string.IsNullOrEmpty(persionKey)) { isEntityType = true; redisKey = string.Format("{0}_{1}", RedisConnectionPool.EncodeTypeName(typeName), entityKey); } else { //私有类型 redisKey = string.Format("{0}_{1}", RedisConnectionPool.EncodeTypeName(typeName), persionKey); } string formatString = entityTypeNameFormat; if (isEntityType) { formatString = "{0},{1}"; } if (type == null) { string entityTypeName = RedisConnectionPool.DecodeTypeName(typeName); type = Type.GetType(string.Format(formatString, entityTypeName, asmName), false, true); if (Equals(type, null)) { var enitityAsm = ScriptEngines.GetEntityAssembly(); if (enitityAsm != null) { asmName = enitityAsm.GetName().Name; type = Type.GetType(string.Format(formatString, entityTypeName, asmName), false, true); if (Equals(type, null)) { //调试模式下type为空处理 type = enitityAsm.GetType(entityTypeName, false, true); } } } } return(entityKey); }
/// <summary> /// The game service start. /// </summary> /// <param name="setting">Environment setting.</param> /// <param name="cacheSetting">Cache setting.</param> public static void Start(EnvironmentSetting setting, CacheSetting cacheSetting) { if (IsRunning) { return; } TraceLog.WriteLine("{0} Server is starting...", DateTime.Now.ToString("HH:mm:ss")); _setting = setting; if (!RedisConnectionPool.Ping("127.0.0.1")) { string error = string.Format("Error: NIC is not connected or no network."); TraceLog.WriteLine(error); TraceLog.WriteError(error); return; } RedisConnectionPool.Initialize(_setting.Serializer); if (!RedisConnectionPool.CheckConnect()) { string error = string.Format("Error: the redis server is not started."); TraceLog.WriteLine(error); TraceLog.WriteError(error); return; } TraceLog.WriteLine("{0} Redis server connect successfully.", DateTime.Now.ToString("HH:mm:ss")); DbConnectionProvider.Initialize(); TraceLog.WriteLine("{0} DB server connect successfully.", DateTime.Now.ToString("HH:mm:ss")); EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod; EntitySchemaSet.CacheUserPeriod = _setting.CacheUserPeriod; if (_setting.EntityAssembly != null) { ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly); EntitySchemaSet.LoadAssembly(_setting.EntityAssembly); } ZyGameBaseConfigManager.Intialize(); //init script. if (_setting.ScriptSysAsmReferences.Length > 0) { ScriptEngines.AddSysReferencedAssembly(_setting.ScriptSysAsmReferences); } ScriptEngines.AddReferencedAssembly("ZyGames.Framework.Game.dll"); if (_setting.ScriptAsmReferences.Length > 0) { ScriptEngines.AddReferencedAssembly(_setting.ScriptAsmReferences); } ScriptEngines.RegisterModelChangedBefore(OnModelChangeBefore); ScriptEngines.RegisterModelChangedAfter(OnModelChangeAtfer); ScriptEngines.OnLoaded += OnScriptLoaded; ScriptEngines.Initialize(); Language.SetLang(); CacheFactory.Initialize(cacheSetting, _setting.Serializer); EntitySchemaSet.StartCheckTableTimer(); Global = new ContextCacheSet <CacheItem>("__gameenvironment_global"); }
public ApplicationDomain(ScriptEngines scriptEngines, string baseDirectory) : base(scriptEngines, baseDirectory) { lazyAssembly = new Utility.Lazy <Assembly>(LoadAssembly); var site = scriptEngines.Site; pathToAssembly = Path.Combine(scriptEngines.RuntimeDirectory, AssemblyName + ".dll"); }
public WatcherScriptDomain(ScriptEngines scriptEngines, string baseDirectory) : base(scriptEngines, baseDirectory) { watcher = new FileSystemWatcher(baseDirectory, Filter); watcher.IncludeSubdirectories = true; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.Changed += new FileSystemEventHandler(WatcherChanged); watcher.EnableRaisingEvents = true; }
public HandleScriptDomain(ScriptEngines scriptDomain, string baseDirectory) : base(scriptDomain, baseDirectory) { if (ScriptEngines.IsDebug) { var scriptAssemblyName = ScriptEngines.Conf.GetString(DebugScriptAssemblyProperty, DefaultScriptAssembly); var scriptAssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, scriptAssemblyName); debugScriptAssembly = new DllScriptAssembly(this, scriptAssemblyPath); } }
protected void Page_Load(object sender, EventArgs e) { try { ScriptEngines.RequestMainProgram(HttpContext.Current); } catch (Exception ex) { TraceLog.WriteError("Service error:{0}", ex); } }
public AppScriptDomain(ScriptEngines scriptEngines, string baseDirectory) : base(scriptEngines, baseDirectory) { lazyAssembly = new Utility.Lazy <Assembly>(this.LoadAssembly); var site = scriptEngines.Site; pathToAssembly = Path.Combine(scriptEngines.RuntimeDirectory, AssemblyName + ".dll"); if (!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } }
/// <summary> /// Set language object. /// </summary> private static void SetLang(string typeName) { var obj = ScriptEngines.ExecuteCSharp(typeName); if (obj != null) { _instance = obj; } else { TraceLog.WriteWarn("Can not find the corresponding language configuration,typeName:{0}", typeName);//By Seamoon } }
/// <summary> /// Proccess stop logic /// </summary> public virtual void OnStop() { try { TraceLog.WriteLine("{0} Server is stopping, please wait.", DateTime.Now.ToString("HH:mm:ss")); ScriptEngines.StopMainProgram(); GameEnvironment.WaitStop().Wait(); TraceLog.WriteLine("{0} Server has stoped successfully!", DateTime.Now.ToString("HH:mm:ss")); } catch (Exception ex) { TraceLog.WriteError("OnStop error:{0}", ex); } }
public static T Create(string formatType, string stepName) { string typeName = string.Format(formatType, stepName); string code = string.Format(ConfigUtils.GetSetting("CaseStep.Script.Format", "Case.Step{0}.cs"), stepName); var instance = ScriptEngines.Execute(code, typeName); //var instance = type.CreateInstance<CaseStep>(); if (instance == null) { throw new NullReferenceException(string.Format("Get CaseStep object is null, type:{1}, script code:{0}", code, typeName)); } instance.Action = stepName; return(instance); }
public async Task <IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode; RequestPackage package; var actionDispatcher = GameEnvironment.Setting.ActionDispatcher; if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode)) { return(new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0])); } GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request); session.ProxySid = package.ProxySid; } else { session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request); } package.Bind(session); ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session); if (package.IsUrlParam) { httpGet["UserHostAddress"] = session.RemoteAddress; httpGet["ssid"] = session.KeyCode.ToString("N"); httpGet["http"] = "1"; } var result = await System.Threading.Tasks.Task.Run <byte[]>(() => { try { return(ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet)); } catch (Exception ex) { TraceLog.WriteError("Excute mainclass error:{0}", ex); return(new byte[0]); } }); return(new ByteResponse(statusCode, "OK", result)); }
protected void Application_Start(object sender, EventArgs e) { try { if (!GameEnvironment.IsRunning) { var setting = new EnvironmentSetting(); GameEnvironment.Start(setting); ScriptEngines.RunMainProgram(); } } catch (Exception ex) { TraceLog.WriteError("App star error:{0}", ex); } }
public override object GetData(JsonParameter[] paramList) { string pythonCode = ""; string pythonFunc = "Main"; string pythonFuncArg = ""; List <KeyValuePair <string, object> > pyParams = new List <KeyValuePair <string, object> >(); foreach (var param in paramList) { switch (param.Key) { case "_py_code": pythonCode = param.Value; break; case "_py_func": pythonFunc = param.Value; break; case "_py_func_arg": pythonFuncArg = param.Value; break; default: if (!string.IsNullOrEmpty(param.Key)) { pyParams.Add(new KeyValuePair <string, object>(param.Key, param.Value)); } break; } } var scope = ScriptEngines.ExecutePythonSource(pythonCode, new string[0]); foreach (var param in pyParams) { scope.SetVariable(param.Key, param.Value); } var func = scope.GetVariable <Func <string, object> >(pythonFunc); if (func != null) { return(func("")); } return(null); //return PythonUtils.CallFunc(pythonFunc, "", pyParams, pythonCode); }
/// <summary> /// Processes the cmd. /// </summary> /// <param name="args">Arguments.</param> protected override void ProcessCmd(string[] args) { string routeName = string.Format("Gm.{0}", _cmd); dynamic scriptScope = ScriptEngines.Execute(routeName, null); if (scriptScope != null) { try { scriptScope.processCmd(UserID, args); } catch (Exception ex) { TraceLog.WriteError("Gm:{0} process error:{1}", _cmd, ex); } } }
/// <summary> /// Call remote method /// </summary> /// <param name="routePath"></param> /// <param name="actionGetter"></param> /// <param name="response"></param> protected virtual void OnCallRemote(string routePath, ActionGetter actionGetter, MessageStructure response) { try { string[] mapList = routePath.Split('.'); string funcName = ""; string routeName = routePath; if (mapList.Length > 1) { funcName = mapList[mapList.Length - 1]; routeName = string.Join("/", mapList, 0, mapList.Length - 1); } string routeFile = ""; int actionId = actionGetter.GetActionId(); MessageHead head = new MessageHead(actionId); if (!ScriptEngines.SettupInfo.DisablePython) { routeFile = string.Format("Remote.{0}", routeName); dynamic scope = ScriptEngines.ExecutePython(routeFile); if (scope != null) { var funcHandle = scope.GetVariable <RemoteHandle>(funcName); if (funcHandle != null) { funcHandle(actionGetter, head, response); response.WriteBuffer(head); return; } } } string typeName = string.Format(TNet.Runtime.GameZone.Setting.RemoteTypeName, routeName); routeFile = string.Format("Remote.{0}", routeName); var args = new object[] { actionGetter, response }; var instance = (object)ScriptEngines.Execute(routeFile, typeName, args); if (instance is RemoteStruct) { var target = instance as RemoteStruct; target.DoRemote(); } } catch (Exception ex) { TraceLog.WriteError("OnCallRemote error:{0}", ex); } }
/// <summary> /// The game service start. /// </summary> /// <param name="setting">Environment setting.</param> /// <param name="cacheSetting">Cache setting.</param> public static void Start(EnvironmentSetting setting, CacheSetting cacheSetting) { if (_isRunning == 1) { return; } _setting = setting; if (!RedisConnectionPool.CheckConnect()) { string error = string.Format("Error: the redis server is not started."); Console.WriteLine(error); TraceLog.WriteError(error); return; } DbConnectionProvider.Initialize(); EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod; EntitySchemaSet.CacheUserPeriod = _setting.CacheUserPeriod; if (_setting.EntityAssembly != null) { ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly); EntitySchemaSet.LoadAssembly(_setting.EntityAssembly); } EntitySchemaSet.StartCheckTableTimer(); LoadGameEntitySchema(); ZyGameBaseConfigManager.Intialize(); //init script. if (_setting.ScriptSysAsmReferences.Length > 0) { ScriptEngines.AddSysReferencedAssembly(_setting.ScriptSysAsmReferences); } ScriptEngines.AddReferencedAssembly("ZyGames.Framework.Game.dll"); if (_setting.ScriptAsmReferences.Length > 0) { ScriptEngines.AddReferencedAssembly(_setting.ScriptAsmReferences); } ScriptEngines.RegisterModelChangedBefore(OnModelChangeBefore); ScriptEngines.RegisterModelChangedAfter(OnModelChangeAtfer); ScriptEngines.Initialize(); Language.SetLang(); CacheFactory.Initialize(cacheSetting); Global = new ContextCacheSet <CacheItem>("__gameenvironment_global"); Interlocked.Exchange(ref _isRunning, 1); }