public static void ActionMessage(IOSession session, int messageid, byte[] buffer) { log.Debug("message id :" + messageid); //验证是否注册消息 if (MessageHandlers.ContainsKey(messageid)) { //获取消息体 MessageBean ins = MessageHandlers[messageid]; // object obj = Activator.CreateInstance(ins.Handler); // if (obj is TcpHandler) { TcpHandler objhandler = (obj as TcpHandler); if (objhandler != null) { objhandler.Session = session; //拷贝字节数组 byte[] msgbuf = new byte[buffer.Length - 4]; for (int i = 0; i < msgbuf.Length; i++) { msgbuf[i] = buffer[i + 4]; } //创建消息 objhandler.Message = MessageHelper.MessageDeserialize(msgbuf, ins.MsgInstance); //将消息放入执行线程 Net.Sz.Framework.SzThreading.ThreadPool.AddTask(ins.ThreadID, objhandler); return; } } } log.Error("尚未注册的消息:" + messageid); }
/// <summary> /// 线程处理器 /// </summary> protected virtual void Run() { while (!this.IsDelete) { while ((taskQueue.Count > 0)) { TaskModel task = null; /*获取并移除当前任务*/ if (!taskQueue.TryDequeue(out task)) { break; } /* 执行任务 */ long submitTime = TimeUtil.CurrentTimeMillis(); try { if (!task.Cancel) { task.Run(); } } catch (Exception e) { if (log.IsErrorEnabled()) { log.Error(System.Threading.Thread.CurrentThread.Name + " 执行任务:" + task.GetType().FullName + " 遇到错误", e); } } if (task is TimerTaskModel) { ((TimerTaskModel)task).LastRun = true; } long timeL1 = TimeUtil.CurrentTimeMillis() - submitTime; if (!task.GetType().FullName.StartsWith("Net.Sz.Framework")) { if (timeL1 > 10) { if (log.IsDebugEnabled()) { log.Debug(System.Threading.Thread.CurrentThread.Name + " 完成了任务:" + task.GetType().FullName + " 执行耗时:" + timeL1); } } } task = null; } are.Reset(); /*队列为空等待200毫秒继续*/ are.WaitOne(200); } if (log.IsErrorEnabled()) { log.Error(DateTime.Now.NowString() + " " + System.Threading.Thread.CurrentThread.Name + " Destroying"); } }
/// <summary> /// 初始化服务器 /// </summary> internal NettyServer(string ip = "0.0.0.0", int port = 9527, int threadcount = 2) { System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port); this._IP = localEP; try { if (log.IsInfoEnabled()) { log.Info(string.Format("Start Listen Tcp Socket -> {0}:{1} ", ip, port)); } /*绑定*/ this._Listeners = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); this._Listeners.Bind(this._IP); this._Listeners.Listen(5000); /*创建线程处理*/ MessageThreadID = Framework.SzThreading.ThreadPool.GetThreadModel("Netty Session Pool Thread:" + ip + ":" + port, SzThreading.SzThread.ThreadType.Sys, threadcount); System.Net.Sockets.SocketAsyncEventArgs sea = new System.Net.Sockets.SocketAsyncEventArgs(); sea.Completed += new EventHandler <System.Net.Sockets.SocketAsyncEventArgs>(this.AcceptAsync_Async); this.AcceptAsync(sea); } catch (Exception ex) { if (log.IsErrorEnabled()) { log.Error("Start Listen Tcp Socket Exception", ex); } this.Dispose(); } }
public void InitializeDatabase() { try { if (log.IsInfoEnabled()) { log.Info("开始创建数据库"); } if (log.IsInfoEnabled()) { log.Info(this.Database.CreateIfNotExists() + ""); } if (log.IsInfoEnabled()) { log.Info("创建数据库完成"); } } catch (Exception ex) { if (log.IsErrorEnabled()) { log.Error("创建数据库失败" + ex); } } }
public override void Run() { session._Action(); if (!"favicon.ico".Equals(session.Http_Url)) { if (log.IsDebugEnabled()) { log.Debug("Create Http Socket Remote Socket LocalEndPoint:" + session.LocalEndPoint + " RemoteEndPoint:" + session.RemoteEndPoint.ToString()); } HttpActionBean httpbean = null; if (!httpServer.httpHandlers.TryGetValue(session.Http_Url, out httpbean)) { httpServer.httpHandlers.TryGetValue("*", out httpbean); } if (httpbean != null) { HttpActionRun taskmodel = new HttpActionRun(session, httpbean.ihttpHandler); ThreadPool.AddTask(httpbean.threadId, taskmodel); return; } if (log.IsErrorEnabled()) { log.Error("未找到监听状态:" + session.Http_Url, new Exception("未找到监听状态:" + session.Http_Url)); } } session.Close(); }
/// <summary> /// /// </summary> public void Start() { try { this._Listeners = new TcpListener(_IP); this._Listeners.Start(5000); this.IsInit = true; this.AcceptAsync(); } catch (Exception ex) { if (log.IsErrorEnabled()) { log.Error("初始化httpserver", ex); } this.Dispose(); } }
/// <summary> /// 接收消息回调函数 /// </summary> /// <param name="iar"></param> internal virtual void ReceiveCallback(IAsyncResult iar) { if (!this.IsDispose) { try { //接受消息 ReceiveSize = _Socket.EndReceive(iar, out ReceiveError); //检查状态码 if (!CheckSocketError(ReceiveError) && SocketError.Success == ReceiveError) { //判断接受的字节数 if (ReceiveSize > 0) { LastRecvTime = Utils.TimeUtil.CurrentTimeMillis(); byte[] rbuff = new byte[ReceiveSize]; Array.Copy(this.Buffers, rbuff, ReceiveSize); var msgs = mershaEncoder.Decoder(this, rbuff); foreach (var msg in msgs) { try { if (NettyPool.MessageThread == 0) { NettyPool.InitMessageThread(); } SzThreading.ThreadPool.AddTask(NettyPool.MessageThread, new IOMessageTask(this, msg)); } catch (Exception ex) { log.Error("处理消息", ex); } } //重置连续收到空字节数 ZeroCount = 0; } else { ZeroCount++; if (ZeroCount == 5) { this.Close("错误链接"); return; } } //继续开始异步接受消息 ReceiveAsync(); } } catch (System.Net.Sockets.SocketException) { this.Close("链接已经被关闭"); return; } catch (System.ObjectDisposedException) { this.Close("链接已经被关闭"); return; } } }
public void InitializeDatabase() { try { log.Info("开始创建数据库"); log.Info(this.Database.CreateIfNotExists() + ""); log.Info("创建数据库完成"); } catch (Exception ex) { log.Error("创建数据库失败" + ex); } }
internal void Process(IHttpHandler httphandler) { try { httphandler.Run(this); if (!this.IsRespons) { log.Error("实现类:" + httphandler.GetType().Name + ",未调用 Respons 函数回复请求"); if (builder == null || builder.Length < 1) { Respons404(); } else { Respons(); } } } catch (Exception e) { log.Error("ActiveHttp Exception: ", e); this.Close(); } }
/// <summary> /// 根据指定的文件动态编译获取实例 /// <para>如果需要加入调试信息,加入代码 System.Diagnostics.Debugger.Break();</para> /// <para>如果传入的是目录。默认只会加载目录中后缀“.cs”文件</para> /// </summary> /// <param name="paths"> /// 可以是目录也可以是文件路径 /// </param> /// <param name="extensionNames">需要加载目录中的文件后缀</param> /// <param name="dllName">加载的附加DLL文件的路径,绝对路径</param> public List <String> LoadCSharpFile(String[] paths, List <String> extensionNames, params String[] dllName) { List <String> retStrs = new List <String>(); if (extensionNames == null) { extensionNames = csExtensionNames; } var asss = AppDomain.CurrentDomain.GetAssemblies(); foreach (var item in asss) { try { if (!item.ManifestModule.IsResource() && !"<未知>".Equals(item.ManifestModule.FullyQualifiedName)) { String ext = System.IO.Path.GetExtension(item.ManifestModule.FullyQualifiedName).ToLower(); if (exts.Contains(ext)) { ddlNames.Add(item.ManifestModule.FullyQualifiedName); } } } catch (Exception ex) { if (log.IsErrorEnabled()) { log.Error("查找需要的dll路径错误1:" + item.ManifestModule.FullyQualifiedName, ex); } } } foreach (var item in dllName) { try { String ext = System.IO.Path.GetExtension(item).ToLower(); if (exts.Contains(ext)) { ddlNames.Add(item); } } catch (Exception ex) { if (log.IsErrorEnabled()) { log.Error("查找需要的dll路径错误2:" + item, ex); } } } if (log.IsDebugEnabled()) { foreach (var item in ddlNames) { try { log.Debug("加载依赖程序集:" + System.IO.Path.GetFileName(item)); } catch (Exception) { if (log.IsErrorEnabled()) { log.Error("加载依赖程序集:" + item); } } } } List <String> fileNames = new List <String>(); ActionPath(paths, extensionNames, ref fileNames); if (fileNames.Count == 0) { retStrs.Add("目录不存在任何脚本文件"); return(retStrs); } CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameter = new CompilerParameters(); //不输出编译文件 parameter.GenerateExecutable = false; //生成调试信息 parameter.IncludeDebugInformation = true; //需要调试必须输出到内存 parameter.GenerateInMemory = true; //添加需要的程序集 parameter.ReferencedAssemblies.AddRange(ddlNames.ToArray()); //System.Environment.CurrentDirectory CompilerResults result = provider.CompileAssemblyFromFile(parameter, fileNames.ToArray());//根据制定的文件加载脚本 if (result.Errors.HasErrors) { var item = result.Errors.GetEnumerator(); while (item.MoveNext()) { if (log.IsErrorEnabled()) { log.Error("动态加载文件出错了!" + item.Current.ToString()); } } } else { Dictionary <string, Dictionary <string, object> > tempInstances = new Dictionary <string, Dictionary <string, object> >(); ActionAssembly(result.CompiledAssembly, tempInstances, retStrs); if (retStrs.Count == 0 && tempInstances.Count > 0) { this.ScriptInstances = tempInstances; } } return(retStrs); }
/// <summary> /// 根据指定的文件动态编译获取实例 /// <para>如果需要加入调试信息,加入代码 System.Diagnostics.Debugger.Break();</para> /// <para>如果传入的是目录。默认只会加载目录中后缀“.cs”文件</para> /// </summary> /// <param name="paths"> /// 可以是目录也可以是文件路径 /// </param> /// <param name="extensionNames">需要加载目录中的文件后缀</param> /// <param name="dllName">加载的附加DLL文件的路径,绝对路径</param> public void LoadCSharpFile(string[] paths, List <String> extensionNames, params string[] dllName) { if (extensionNames == null) { extensionNames = csExtensionNames; } List <String> fileNames = new List <String>(); ActionPath(paths, extensionNames, ref fileNames); if (fileNames.Count == 0) { return; } var asss = AppDomain.CurrentDomain.GetAssemblies(); foreach (var item in asss) { if (!item.ManifestModule.IsResource() && item.ManifestModule.FullyQualifiedName.EndsWith(".dll") || item.ManifestModule.FullyQualifiedName.EndsWith(".DLL")) { ddlNames.Add(item.ManifestModule.FullyQualifiedName); } } foreach (var item in dllName) { if (item.EndsWith(".dll") || item.EndsWith(".DLL")) { ddlNames.Add(item); } } foreach (var item in ddlNames) { try { if (log.IsInfoEnabled()) { log.Info("加载DLL:" + item); } } catch { } } CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters parameter = new CompilerParameters(); //不输出编译文件 parameter.GenerateExecutable = false; //生成调试信息 parameter.IncludeDebugInformation = true; //需要调试必须输出到内存 parameter.GenerateInMemory = true; //添加需要的程序集 parameter.ReferencedAssemblies.AddRange(ddlNames.ToArray()); CompilerResults result = provider.CompileAssemblyFromFile(parameter, fileNames.ToArray());//根据制定的文件加载脚本 if (result.Errors.HasErrors) { var item = result.Errors.GetEnumerator(); while (item.MoveNext()) { if (log.IsErrorEnabled()) { log.Error("动态加载文件出错了!" + item.Current.ToString()); } } } else { ActionAssembly(result.CompiledAssembly); } }