void GetContextCallBack(IAsyncResult ar) { HttpListener listener = ar.AsyncState as HttpListener; listener.BeginGetContext(new AsyncCallback(GetContextCallBack), listener); try { HttpListenerContext context = listener.EndGetContext(ar); //Thread procThr = new Thread(() => procContext(context)); //procThr.IsBackground = true; //procThr.Start(); //procContext(context); ThreadPool.QueueUserWorkItem(o => { HttpListenerContext c = o as HttpListenerContext; procContext(c); }, context); } catch (Exception ex) { DCLogger.LogError("listener.BeginGetContext error:{0}", ex.Message); } //finally //{ // listener.BeginGetContext(new AsyncCallback(GetContextCallBack), listener); //} }
public void Start() { IConfigSource cs = new IniConfigSource(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConnectorRest.ini")); // 检查系统是否支持 if (!HttpListener.IsSupported) { DCLogger.LogError("软件运行需要 Windows XP SP2 或 Server 2003 以上系统."); } // 注意前缀必须以 / 正斜杠结尾 string[] prefixes = cs.Configs["init"].Get("ListenPoint").Split(','); // 设置manifest UAC权限 foreach (string lsnrUrl in prefixes) { AddAddress(lsnrUrl); } // 增加监听的前缀. foreach (string lsnrUrl in prefixes) { listener.Prefixes.Add(lsnrUrl); } //开始监听 try { listener.Start(); } catch (Exception ex) { DCLogger.LogError(ex.Message); throw ex; } foreach (string lsnrUrl in prefixes) { DCLogger.LogInfo(string.Format("REST监听启动于:{0}", lsnrUrl)); } //for (int i = 0; i < 60; i++) { try { listener.BeginGetContext(new AsyncCallback(GetContextCallBack), listener); } catch (Exception ex) { DCLogger.LogError("listener.BeginGetContext error:{0}", ex.Message); } } Console.Read(); }
void AddAddress(string address) { try { AddAddress(address, Environment.UserDomainName, Environment.UserName); } catch (Exception ex) { DCLogger.LogError(ex.Message); } }
public void Stop() { try { //listener.Stop(); listener.Close(); } catch (Exception ex) { DCLogger.LogError(ex.Message); throw ex; } }
private Dictionary <string, IBizSrv> getBizs() { Dictionary <string, IBizSrv> result = new Dictionary <string, IBizSrv>(); //获取项目根目录下的Plugins文件夹 string dir = Directory.GetCurrentDirectory(); //遍历目标文件夹中包含dll后缀的文件 foreach (var file in Directory.GetFiles(dir + @"\", "*.dll")) { try { //加载程序集 var asm = Assembly.LoadFrom(file); //遍历程序集中的类型 foreach (var type in asm.GetTypes()) { //如果是IBizSrv接口 if (type.GetInterfaces().Contains(typeof(IBizSrv))) { //创建接口类型实例 var ibiz = Activator.CreateInstance(type) as IBizSrv; var sign = "/" + Path.GetFileNameWithoutExtension(file).Replace('.', '/'); if (ibiz != null) { result.Add(sign, ibiz); } } } } catch (Exception e) { DCLogger.LogError("Recognise {0} failed for:{1}", file, e.Message); continue; } } return(result); }
private byte[] dic_list(string extInfo, byte[] req) { DicListQry para; byte[] checkResult = PackOrb.CheckRequest <DicListQry>(req, out para, new string[] { "dicname", }); if (checkResult != null) { return(checkResult); } #region 查询字典信息 try { string dicTbl = null; switch (para.dicname) { case "蔬菜名称": dicTbl = "t_dic_vegname"; break; case "蔬菜种类": dicTbl = "t_dic_vegtype"; break; default: return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.ServerSideError, }, new ListDictionary { { "respnum", -2 }, { "respmsg", "不存在此字典" }, } )); } QueryCommandConfig CmdConfig = new QueryCommandConfig(string.Format("select * from {0} order by code", dicTbl)); DataTable dt = db.GetDataTable(CmdConfig); return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.Succeed, }, new ListDictionary { { "respnum", dt.Rows.Count }, { "respmsg", "获取字典成功" }, { "count", dt.Rows.Count }, { "data", dt }, } )); } catch (Exception e) { DCLogger.LogError(e.Message); return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.ServerSideError, }, new ListDictionary { { "respnum", -2 }, { "respmsg", e.Message }, } )); } #endregion }
public void LogError(string message, params object[] args) { DCLogger.LogError(string.Format("from [{0}]:{1}", bizSrvName, message), args); }
public void LogError(string message) { DCLogger.LogError(string.Format("from [{0}]:{1}", bizSrvName, message)); }
private void procContext(HttpListenerContext context) { // 取得请求对象 HttpListenerRequest request = context.Request; // 取得回应对象 HttpListenerResponse response = context.Response; try { //if (request.RawUrl.Equals("/helloworld")) //{ // byte[] ack = Encoding.UTF8.GetBytes("Hello World!"); // response.ContentLength64 = ack.LongLength; // response.ContentType = "text/plain; charset=UTF-8"; // response.StatusCode = 200; // // 输出回应内容 // using (BinaryWriter writer = new System.IO.BinaryWriter(response.OutputStream)) // { // writer.Write(ack, 0, (int)response.ContentLength64); // } // return; //} //if (request.ContentLength64 < 0 || request.ContentLength64 > 20000000) //{ // string resp = string.Format("无效的Rest请求内容长度:{0}", request.ContentLength64); // byte[] respbytes = Encoding.UTF8.GetBytes(resp); // DCLogger.LogError(resp); // // 设置回应头部内容,长度,编码 // response.ContentLength64 = respbytes.LongLength; // response.ContentType = "text/plain; charset=UTF-8"; // response.StatusCode = 500; // // 输出回应内容 // try // { // using (BinaryWriter writer = new BinaryWriter(response.OutputStream)) // { // writer.Write(respbytes, 0, (int)response.ContentLength64); // } // } // catch (Exception ex) // { // DCLogger.LogError(ex.Message); // } // return; //} byte[] postData = parseRequest(request); client.Act(request.RawUrl, postData, (rst) => { issueResponse(request, response, rst); } ); } catch (Exception ex) { // 设置回应头部内容,长度,编码 byte[] respbytes = Encoding.UTF8.GetBytes(ex.Message); response.ContentLength64 = respbytes.LongLength; response.ContentType = "text/plain; charset=UTF-8"; response.StatusCode = 500; // 输出回应内容 try { if (ex is MissingMethodException) { DCLogger.LogTrace(ex.Message); } else { DCLogger.LogError(ex.Message); } using (BinaryWriter writer = new BinaryWriter(response.OutputStream)) { writer.Write(respbytes, 0, (int)response.ContentLength64); } } catch (Exception ex2) { DCLogger.LogError(ex2.Message); } //response.Close(); } }
private static void issueResponse(HttpListenerRequest request, HttpListenerResponse response, ActResult rst) { if (rst.Exception != null) { rst.ResultData = PackOrb.PackRespose( new HttpHeadInfo { StatusCode = BizUtils.Rest.HttpStatusCode.ServerSideError }, new ListDictionary { { "respnum", -1 }, { "respmsg", rst.Exception }, } ); DCLogger.LogError("issueResponse get a biz srv error:{0}", rst.Exception.Message); } // 设置回应头部内容,长度,编码 int httpHeadInfoLength = BitConverter.ToInt32(rst.ResultData, 0); HttpHeadInfo httpHeadInfo = HttpHeadInfo.FromBytes(rst.ResultData, 4, httpHeadInfoLength); int rawBytesIndex = httpHeadInfoLength + 4; response.ContentLength64 = rst.ResultData.LongLength - rawBytesIndex; response.ContentType = httpHeadInfo.ContentType; response.StatusCode = (int)httpHeadInfo.StatusCode; // 输出回应内容 try { using (BinaryWriter writer = new BinaryWriter(response.OutputStream)) { writer.Write(rst.ResultData, rawBytesIndex, (int)response.ContentLength64); } } catch (Exception ex) { DCLogger.LogError(ex.Message); } if (response.ContentType.Equals(HttpContentType.Json)) { if (response.ContentLength64 > logTxtLen) { if (response.StatusCode == (int)BizUtils.Rest.HttpStatusCode.Succeed) { DCLogger.LogTrace(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, logTxtLen) + "..." ) ); } else { DCLogger.LogWarn(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, logTxtLen) + "..." ) ); } } else { if (response.StatusCode == (int)BizUtils.Rest.HttpStatusCode.Succeed) { DCLogger.LogTrace(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, (int)response.ContentLength64) ) ); } else { DCLogger.LogWarn(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, (int)response.ContentLength64) ) ); } } } }
private byte[] manage_register(string extInfo, byte[] req) { RegisterData para; byte[] checkResult = PackOrb.CheckRequest <RegisterData>(req, out para, new string[] { "MobileNumber", "Account", "Password", }); if (checkResult != null) { return(checkResult); } if (!Regex.IsMatch(para.Account, "^[A-Za-z][A-Za-z0-9_]*$")) { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.BadRequest, }, new ListDictionary { { "respnum", -1 }, { "respmsg", "帐号必须以英文字母开始,且只能由英文、数字和下划线组成" }, } )); } if (!Regex.IsMatch(para.MobileNumber, "^[0-9]*$")) { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.BadRequest, }, new ListDictionary { { "respnum", -1 }, { "respmsg", "手机号必须以数字组成" }, } )); } #region 保存register信息 long ret = 0; string mb_guid = Guid.NewGuid().ToString("N"); try { QueryCommandConfig QryCmdConfig = new QueryCommandConfig("select count(*) from t_mobapp_reginfo where MobileNumber = @MobileNumber or Account = @Account"); QryCmdConfig.Params["MobileNumber"] = para.MobileNumber; QryCmdConfig.Params["Account"] = para.Account; object ob = db.ExecuteScalar(QryCmdConfig); if (ob != null && Int32.Parse(ob.ToString()) > 0) { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.BadRequest, }, new ListDictionary { { "respnum", -1 }, { "respmsg", "该手机号或帐号已注册" }, } )); } CommandConfig CmdConfig = new CommandConfig("t_mobapp_reginfo"); CmdConfig.Params["mb_guid"] = mb_guid; CmdConfig.Params["MobileNumber"] = para.MobileNumber; CmdConfig.Params["Account"] = para.Account; CmdConfig.Params["Password"] = para.Password; ret -= db.ExecuteInsert(CmdConfig); } catch (Exception e) { DCLogger.LogError(e.Message); return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.ServerSideError, }, new ListDictionary { { "respnum", -2 }, { "respmsg", e.Message }, } )); } return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.Succeed, }, new ListDictionary { { "respnum", ret }, { "respmsg", "用户注册成功" }, { "mb_guid", mb_guid }, } )); #endregion }
private byte[] manage_login(string extInfo, byte[] req) { ClientLogin para; byte[] checkResult = PackOrb.CheckRequest <ClientLogin>(req, out para, new string[] { "LoginName", "Password", }); if (checkResult != null) { return(checkResult); } #region 登录验证 try { string loginCol = "Account"; if (Regex.IsMatch(para.LoginName, "^[0-9]*$")) { loginCol = "MobileNumber"; } QueryCommandConfig CmdConfig = new QueryCommandConfig(string.Format("select mb_guid,Password from t_mobapp_reginfo where {0} = @LoginName", loginCol)); CmdConfig.Params["LoginName"] = para.LoginName; DataTable dt = db.GetDataTable(CmdConfig); if (dt.Rows.Count == 0) { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.BadRequest, }, new ListDictionary { { "respnum", -1 }, { "respmsg", "未找到此用户" }, } )); } if (dt.Rows[0]["Password"].ToString().Equals(para.Password)) { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.Succeed, }, new ListDictionary { { "respnum", 1 }, { "respmsg", "用户登录成功" }, { "mb_guid", dt.Rows[0]["mb_guid"].ToString() }, } )); } else { return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.BadRequest, }, new ListDictionary { { "respnum", -1 }, { "respmsg", "密码错误" }, } )); } } catch (Exception e) { DCLogger.LogError(e.Message); return(PackOrb.PackRespose( new HttpHeadInfo { StatusCode = HttpStatusCode.ServerSideError, }, new ListDictionary { { "respnum", -2 }, { "respmsg", e.Message }, } )); } #endregion }
//private string lsnrUrl = "http://+:8080/"; //private string localMngPort = "8090"; public void Start() { IConfigSource cs = new IniConfigSource(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConnectorRest.ini")); //lsnrUrl = cs.Configs["init"].Get("ListenPoint"); //localMngPort = cs.Configs["init"].Get("LocalManagePort"); lsnrThrd = new Thread(new ThreadStart(delegate() { // 检查系统是否支持 if (!HttpListener.IsSupported) { DCLogger.LogError("软件运行需要 Windows XP SP2 或 Server 2003 以上系统."); } // 注意前缀必须以 / 正斜杠结尾 string[] prefixes = cs.Configs["init"].Get("ListenPoint").Split(','); // 设置manifest UAC权限 foreach (string lsnrUrl in prefixes) { AddAddress(lsnrUrl); } // 创建监听器. HttpListener listener = new HttpListener(); // 增加监听的前缀. foreach (string lsnrUrl in prefixes) { listener.Prefixes.Add(lsnrUrl); } //开始监听 try { listener.Start(); } catch (Exception ex) { DCLogger.LogError(ex.Message); throw ex; } foreach (string lsnrUrl in prefixes) { DCLogger.LogInfo(string.Format("REST监听启动于:{0}", lsnrUrl)); } DCClient client = DCClient.Instance("ConnectorRest", "global"); long length = 0; Stopwatch watch = new Stopwatch(); watch.Start(); while (true) { try { // 注意: GetContext 方法将阻塞线程,直到请求到达 HttpListenerContext context = listener.GetContext(); // 取得请求对象 HttpListenerRequest request = context.Request; length += 1; if (watch.ElapsedMilliseconds > 10000) { DCLogger.LogInfo(string.Format("Connect Pressure:{0}requests/s\t{1}", length * 1000 / (watch.ElapsedMilliseconds), DateTime.Now)); length = 0; watch.Reset(); watch.Start(); } //if (request.RawUrl.Equals("/connector/stop")) // break; if (request.RawUrl.Equals("/helloworld")) { // 取得回应对象 HttpListenerResponse response = context.Response; byte[] ack = Encoding.UTF8.GetBytes("Hello World!"); response.ContentLength64 = ack.LongLength; response.ContentType = "text/plain; charset=UTF-8"; response.StatusCode = 200; // 输出回应内容 try { using (BinaryWriter writer = new System.IO.BinaryWriter(response.OutputStream)) { writer.Write(ack, 0, (int)response.ContentLength64); } } catch (Exception ex) { DCLogger.LogError(ex.Message); } continue; } if (request.ContentLength64 < 0 || request.ContentLength64 > 20000000) { string resp = string.Format("超长的Rest请求内容,长度{0}", request.ContentLength64); DCLogger.LogError(resp); // 取得回应对象 HttpListenerResponse response = context.Response; // 设置回应头部内容,长度,编码 response.ContentLength64 = resp.Length; response.ContentType = "text/plain; charset=UTF-8"; response.StatusCode = 500; // 输出回应内容 try { using (BinaryWriter writer = new BinaryWriter(response.OutputStream)) { writer.Write(Encoding.UTF8.GetBytes(resp)); } } catch (Exception ex) { DCLogger.LogError(ex.Message); } continue; } byte[] postData = getPostData(request); if (request.ContentLength64 > 0 && request.ContentLength64 <= 256) { DCLogger.LogTrace(string.Format( "{0}-->{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(postData) ) ); } else if (request.ContentLength64 > 256 && request.ContentLength64 <= 4096) { DCLogger.LogTrace(string.Format( "{0}-->{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(postData, 0, 256) + "..." ) ); } else { DCLogger.LogTrace(string.Format( "{0}-->{1}:::{2}", request.RemoteEndPoint, request.RawUrl, string.Format("{0} bytes long content.", request.ContentLength64) ) ); } //if (postData == null) //{ // HttpListenerResponse response = context.Response; // response.StatusCode = 404; // response.Close(); //} //else { try { client.Act(request.RawUrl, postData, (rst) => { // 取得回应对象 HttpListenerResponse response = context.Response; // 设置回应头部内容,长度,编码 int httpHeadInfoLength = BitConverter.ToInt32(rst.ResultData, 0); HttpHeadInfo httpHeadInfo = HttpHeadInfo.FromBytes(rst.ResultData, 4, httpHeadInfoLength); int rawBytesIndex = httpHeadInfoLength + 4; response.ContentLength64 = rst.ResultData.LongLength - rawBytesIndex; response.ContentType = httpHeadInfo.ContentType; response.StatusCode = (int)httpHeadInfo.StatusCode; // 输出回应内容 try { using (BinaryWriter writer = new System.IO.BinaryWriter(response.OutputStream)) { writer.Write(rst.ResultData, rawBytesIndex, (int)response.ContentLength64); } if (response.ContentType.Equals(HttpContentType.Json)) { if (response.ContentLength64 > 256) { DCLogger.LogTrace(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, 256) + "..." ) ); } else { DCLogger.LogTrace(string.Format( "{0}<--{1}:::{2}", request.RemoteEndPoint, request.RawUrl, Global.Encoding.GetString(rst.ResultData, rawBytesIndex, (int)response.ContentLength64) ) ); } } } catch (Exception ex) { DCLogger.LogError(ex.Message); } } ); } catch (Exception ex) { DCLogger.LogError(ex.Message); // 取得回应对象 HttpListenerResponse response = context.Response; // 设置回应头部内容,长度,编码 response.ContentLength64 = ex.Message.Length; response.ContentType = "text/plain; charset=UTF-8"; response.StatusCode = 500; // 输出回应内容 try { using (BinaryWriter writer = new BinaryWriter(response.OutputStream)) { writer.Write(Encoding.UTF8.GetBytes(ex.Message)); } } catch (Exception ex2) { DCLogger.LogError(ex2.Message); } //response.Close(); } } } catch (ThreadAbortException) { break; } catch { } } // 关闭服务器 listener.Stop(); DCLogger.LogInfo(string.Format("REST监听关闭:{0}", prefixes)); DCClient.Dispose(client); } )); lsnrThrd.IsBackground = true; lsnrThrd.Start(); }