private void DispatchMessage(Message message) { if (message.IsMessage(MessageType.UDPQUERYBAG)) { UDPRevResultMessage revmsg = EntityBufCore.DeSerialize <UDPRevResultMessage>(message.MessageBuffer); var respmsg = new Message(MessageType.UDPANSWERBAG); bool isreved = false; revmsg.Miss = GetMissSegment(revmsg.BagId, null, out isreved); revmsg.IsReved = isreved; respmsg.SetMessageBody(revmsg); SendMessage(respmsg, null); } else if (message.IsMessage(MessageType.UDPANSWERBAG)) { UDPRevResultMessage revmsg = EntityBufCore.DeSerialize <UDPRevResultMessage>(message.MessageBuffer); AutoReSetEventResult wait = null; if (_resetevent.TryGetValue(revmsg.BagId, out wait)) { wait.WaitResult = revmsg; wait.IsTimeOut = false; wait.Set(); } } else { OnMessage(message); } }
private void CreateMessagePipeline(IPEndPoint endpoint, PipelineManualResetEventSlim slim, long bagid, string pipelinekey) { new Action(() => { int trytimes = 0; try { while (true) { slim.Reset(); slim.Wait(30000); if (!slim.IsTimeOut) { var message = EntityBufCore.DeSerialize <Message>(slim.MsgBuffer); DispatchMessage(message, endpoint); break; } else { trytimes++; if (trytimes >= TimeOutTryTimes) { throw new TimeoutException(); } } } } finally { _pipelineSlimDic.Remove(pipelinekey); ClearTempBag(bagid, endpoint); } }).BeginInvoke(null, null); }
private void DispatchMessage(Message message, IPEndPoint endpoint) { if (message.IsMessage(MessageType.UDPQUERYBAG)) { UDPRevResultMessage revmsg = EntityBufCore.DeSerialize <UDPRevResultMessage>(message.MessageBuffer); var respmsg = new Message(MessageType.UDPANSWERBAG); bool isreved = false; revmsg.Miss = GetMissSegment(revmsg.BagId, endpoint, out isreved); revmsg.IsReved = isreved; respmsg.SetMessageBody(revmsg); SendMessage(respmsg, endpoint); } else if (message.IsMessage(MessageType.UDPANSWERBAG)) { UDPRevResultMessage revmsg = EntityBufCore.DeSerialize <UDPRevResultMessage>(message.MessageBuffer); AutoReSetEventResult wait = null; string key = string.Format("{0}:{1}:{2}", endpoint.Address.ToString(), endpoint.Port, revmsg.BagId); if (_resetevent.TryGetValue(key, out wait)) { wait.WaitResult = revmsg; wait.IsTimeOut = false; wait.Set(); } } else if (message.IsMessage(MessageType.UPDSETMTU)) { var mtu = EntityBufCore.DeSerialize <UDPSetMTUMessage>(message.MessageBuffer).MTU; if (mtu < MTU_MIN) { mtu = MTU_MIN; } if (mtu > MTU_MAX) { mtu = MTU_MAX; } lock (_MTUDic) { var key = endpoint.Address.ToString(); if (_MTUDic.ContainsKey(key)) { _MTUDic[key] = mtu; } else { _MTUDic.Add(key, mtu); } } } else if (message.IsMessage(MessageType.UDPCLEARBAGID)) { ClearTempData(endpoint); } else { FromApp(message, endpoint); } }
/// <summary> /// 需要实现DoMessage /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message"></param> /// <param name="timeOut"></param> /// <returns></returns> public T SendMessageAnsy <T>(Message message, int timeOut = 30000) { if (string.IsNullOrEmpty(message.MessageHeader.TransactionID)) { throw new Exception("消息没有设置唯一的序号。无法进行同步。"); } string reqID = message.MessageHeader.TransactionID; using (AutoReSetEventResult autoResetEvent = new AutoReSetEventResult(reqID)) { watingEvents.TryAdd(reqID, autoResetEvent); BuzException = null; SendMessage(message); //new Func<Message, bool>(SendMessage).BeginInvoke(message, null, null); WaitHandle.WaitAny(new WaitHandle[] { autoResetEvent }, timeOut); AutoReSetEventResult removedicitem = null; watingEvents.TryRemove(reqID, out removedicitem); if (BuzException != null) { throw BuzException; } if (autoResetEvent.IsTimeOut) { var ex = new TimeoutException(); ex.Data.Add("errorsender", "LJC.FrameWork.SocketApplication.SocketSTD.SessionClient"); ex.Data.Add("MessageType", message.MessageHeader.MessageType); ex.Data.Add("TransactionID", message.MessageHeader.TransactionID); ex.Data.Add("ipString", this.ipString); ex.Data.Add("ipPort", this.ipPort); if (message.MessageBuffer != null) { ex.Data.Add("MessageBuffer", Convert.ToBase64String(message.MessageBuffer)); } ex.Data.Add("resulttype", typeof(T).FullName); //LogManager.LogHelper.Instance.Error("SendMessageAnsy", ex); throw ex; } else { if (autoResetEvent.DataException != null) { throw autoResetEvent.DataException; } try { T result = EntityBufCore.DeSerialize <T>((byte[])autoResetEvent.WaitResult); return(result); } catch (Exception ex) { Exception e = new Exception("解析消息体失败:" + reqID, ex); e.Data.Add("messageid", reqID); throw e; } } } }
private void CreateMessagePipeline(PipelineManualResetEventSlim slim, long bagid) { new Action(() => { try { slim.Reset(); slim.Wait(30000); if (!slim.IsTimeOut) { var message = EntityBufCore.DeSerialize <Message>(slim.MsgBuffer); DispatchMessage(message); } else { Console.Write("接收超时:" + bagid); OnError(new TimeoutException("接收超时")); } } finally { ClearTempBag(bagid, null); _pipelineSlimDic.Remove(bagid); } }).BeginInvoke(null, null); }
public override bool Process(HttpServer server, HttpRequest request, HttpResponse response) { string json = string.Empty; var apiType = typeof(APIResult <>); var apiResultType = _hander._requestType; json = JsonUtil <object> .Serialize(EntityBufCore.DeSerialize(apiResultType, EntityBufCoreEx.GenSerialize(apiResultType), false), true); StringBuilder sb = new StringBuilder(); sb.Append("<html>"); sb.Append("<body>"); sb.Append("<pre>" + json + "</pre>"); sb.Append("</body>"); sb.Append(@"<script> var ifr=parent&&parent.document.getElementById('req'); if(ifr) { ifr.height=document.body.scrollHeight; } </script>"); response.Content = sb.ToString(); response.ReturnCode = 200; return(true); }
private void ProcessMessage(object buffer) { try { byte[] data = (byte[])buffer; if (!string.IsNullOrWhiteSpace(this.encryKey)) { data = AesEncryHelper.AesDecrypt(data, this.encryKey); } Message message = EntityBufCore.DeSerialize <Message>(data); if (message.IsMessage(MessageType.NEGOTIATIONENCRYR)) { var nmsg = message.GetMessageBody <NegotiationEncryMessage>(); this.encryKey = Encoding.ASCII.GetString(RsaEncryHelper.RsaDecrypt(Convert.FromBase64String(nmsg.EncryKey), this.rsaRrivateKey)); Console.WriteLine("收到加密串:" + encryKey); _startSign.Set(); } else { OnMessage(message); } } catch (Exception e) { OnError(e); } }
/// 需要实现DoMessage /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message"></param> /// <param name="timeOut"></param> /// <returns></returns> public T SendMessageAnsy <T>(Message message, int timeOut = 30000) { if (string.IsNullOrEmpty(message.MessageHeader.TransactionID)) { throw new Exception("消息没有设置唯一的序号。无法进行同步。"); } string reqID = message.MessageHeader.TransactionID; using (AutoReSetEventResult autoResetEvent = new AutoReSetEventResult(reqID)) { watingEvents.Add(reqID, autoResetEvent); BuzException = null; SendMessage(message, null); //ThreadPool.QueueUserWorkItem(new WaitCallback(o => { SendMessage((Message)o); }), message); //new Func<Message, bool>(SendMessage).BeginInvoke(message, null, null); autoResetEvent.WaitOne(timeOut); //WaitHandle.WaitAny(new WaitHandle[] { autoResetEvent }, timeOut); watingEvents.Remove(reqID); if (BuzException != null) { BuzException.Data.Add("MessageType", message.MessageHeader.MessageType); BuzException.Data.Add("TransactionID", message.MessageHeader.TransactionID); throw BuzException; } if (autoResetEvent.IsTimeOut) { var ex = new TimeoutException(); ex.Data.Add("errorsender", "LJC.FrameWork.SocketApplication.SocketEasyUDP.Client.SessionClient"); ex.Data.Add("MessageType", message.MessageHeader.MessageType); ex.Data.Add("TransactionID", message.MessageHeader.TransactionID); if (SessionContext != null) { ex.Data.Add("SessionContext.IPAddress", this.SessionContext.IPAddress); ex.Data.Add("SessionContext.Port", this.SessionContext.Port); } if (message.MessageBuffer != null) { ex.Data.Add("MessageBuffer", Convert.ToBase64String(message.MessageBuffer)); } ex.Data.Add("resulttype", typeof(T).FullName); LogManager.LogHelper.Instance.Error("SendMessageAnsy", ex); throw ex; } else { T result = EntityBufCore.DeSerialize <T>((byte[])autoResetEvent.WaitResult); return(result); } } }
protected override void FromApp(SocketApplication.Message message, SocketApplication.Session session) { if (message.IsMessage((int)SOAMessageType.DoSOARedirectRequest)) { try { if (DoResponseAction != null) { var reqbag = EntityBufCore.DeSerialize <SOARedirectRequest>(message.MessageBuffer); var obj = DoResponseAction(reqbag.FuncId, reqbag.Param, session.SessionID); if (!string.IsNullOrWhiteSpace(message.MessageHeader.TransactionID)) { var retmsg = new SocketApplication.Message((int)SOAMessageType.DoSOARedirectResponse); retmsg.MessageHeader.TransactionID = message.MessageHeader.TransactionID; SOARedirectResponse resp = new SOARedirectResponse(); resp.IsSuccess = true; resp.ResponseTime = DateTime.Now; resp.Result = EntityBuf.EntityBufCore.Serialize(obj); retmsg.SetMessageBody(resp); session.SendMessage(retmsg); } else { throw new Exception("服务未实现"); } } } catch (Exception ex) { var retmsg = new SocketApplication.Message((int)SOAMessageType.DoSOARedirectResponse); retmsg.MessageHeader.TransactionID = message.MessageHeader.TransactionID; SOARedirectResponse resp = new SOARedirectResponse(); resp.IsSuccess = false; resp.ResponseTime = DateTime.Now; resp.ErrMsg = ex.ToString(); retmsg.SetMessageBody(resp); try { session.SendMessage(retmsg); } catch (Exception exx) { OnError(exx); } } } else { base.FromApp(message, session); } }
public override object DoResponse(int funcId, byte[] Param, string clientid) { switch (funcId) { case Consts.Fun_GetChinaCityList: { var req = EntityBufCore.DeSerialize <GetChinaCityListRequest>(Param); return(new WebApiDomain().GetChineseCityInfos(req)); } } return(base.DoResponse(funcId, Param, clientid)); }
private void ProcessMessage(object buffer) { try { byte[] data = (byte[])buffer; Message message = EntityBufCore.DeSerialize <Message>(data); OnMessage(message); } catch (Exception e) { OnError(e); } }
private void OnSocket(object obj) { Socket socket = (Socket)obj; socket.NoDelay = true; IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint; Session appSocket = new Session(); appSocket.IPAddress = endPoint.Address.ToString(); appSocket.IsValid = true; appSocket.SessionID = SocketApplicationComm.GetSeqNum(); appSocket.Socket = socket; while (appSocket.IsValid && appSocket.Socket.Connected) { try { var buffer = ReceivingNext(socket); //搞成异步的 new Action <byte[], Session>((b, s) => { Message message = EntityBufCore.DeSerialize <Message>(b); s.LastSessionTime = DateTime.Now; FormApp(message, s); }).BeginInvoke(buffer, appSocket, null, null); } catch (SessionAbortException exp) { SocketApplicationComm.Debug(exp.Message); break; } catch (SocketException exp) { SocketApplicationComm.Debug(exp.Message); break; } catch (Exception exp) { SocketApplicationComm.Debug(exp.Message); OnError(exp); } } socket.Shutdown(SocketShutdown.Both); socket.Close(); SocketApplicationComm.Debug(string.Format("服务器关闭套接字:{0}", appSocket.SessionID)); }
private void ProcessMultiCastMessage(object buffer) { try { byte[] data = (byte[])buffer; Message message = EntityBufCore.DeSerialize <Message>(data); if (OnMultiCast != null) { OnMultiCast(message); } } catch (Exception e) { } }
private void OnMessage(byte[] data) { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((o) => { var margebytes = MargeBag(data, null); if (margebytes != null) { var bagid = GetBagId(data); SendEcho(bagid); if (data.Length >= margebytes.Length) { var message = EntityBufCore.DeSerialize <Message>(margebytes); DispatchMessage(message); } else { //发送管道通知 PipelineManualResetEventSlim slim = null; //通知管道 if (_pipelineSlimDic.TryGetValue(bagid, out slim)) { slim.MsgBuffer = margebytes; slim.Set(); } } } else { //创建管道 var bagid = GetBagId(data); PipelineManualResetEventSlim slim = null; if (!_pipelineSlimDic.TryGetValue(bagid, out slim)) { lock (_pipelineSlimDic) { if (!_pipelineSlimDic.TryGetValue(bagid, out slim)) { slim = new PipelineManualResetEventSlim(); slim.BagId = bagid; _pipelineSlimDic.Add(bagid, slim); CreateMessagePipeline(slim, bagid); } } } } })); }
public T SendMessageAnsy <T>(Session s, Message message, int timeOut = 60000) { if (string.IsNullOrEmpty(message.MessageHeader.TransactionID)) { throw new Exception("消息没有设置唯一的序号。无法进行同步。"); } string reqID = message.MessageHeader.TransactionID; using (AutoReSetEventResult autoResetEvent = new AutoReSetEventResult(reqID)) { watingEvents.Add(reqID, autoResetEvent); if (s.SendMessage(message)) { WaitHandle.WaitAny(new WaitHandle[] { autoResetEvent }, timeOut); watingEvents.Remove(reqID); if (autoResetEvent.IsTimeOut) { var ex = new TimeoutException(); ex.Data.Add("errorsender", "LJC.FrameWork.SocketApplication.SocketSTD.SessionServer"); ex.Data.Add("MessageType", message.MessageHeader.MessageType); ex.Data.Add("TransactionID", message.MessageHeader.TransactionID); ex.Data.Add("ipString", this.ipString); ex.Data.Add("ipPort", this.ipPort); if (message.MessageBuffer != null) { ex.Data.Add("MessageBuffer", Convert.ToBase64String(message.MessageBuffer)); } ex.Data.Add("resulttype", typeof(T).FullName); //LogManager.LogHelper.Instance.Error("SendMessageAnsy", ex); throw ex; } else { T result = EntityBufCore.DeSerialize <T>((byte[])autoResetEvent.WaitResult); return(result); } } else { throw new Exception("发送失败。"); } } }
protected virtual void FromSessionMessage(Message message, UDPSession session) { if (message.IsMessage(MessageType.SENDFILE)) { var sendfilemsg = EntityBufCore.DeSerialize <SendFileMessage>(message.MessageBuffer); var dir = AppDomain.CurrentDomain.BaseDirectory + "\\file\\"; if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } using (System.IO.FileStream fs = new System.IO.FileStream(dir + sendfilemsg.FileName, System.IO.FileMode.OpenOrCreate)) { fs.Position = fs.Length; fs.Write(sendfilemsg.FileBytes, 0, sendfilemsg.FileBytes.Length); } Message sendfileecho = new Message(MessageType.SENDFILEECHO); sendfileecho.MessageHeader.TransactionID = message.MessageHeader.TransactionID; sendfileecho.SetMessageBody(new SendFileECHOMessage { IsSuccess = true }); SendMessage(sendfileecho, session.EndPoint); } else if (message.IsMessage(MessageType.SENDFILRESENDCHECK)) { var request = EntityBufCore.DeSerialize <SendFileCheckRequestMessage>(message.MessageBuffer); var dir = AppDomain.CurrentDomain.BaseDirectory + "\\file\\"; var fileinofo = new System.IO.FileInfo(dir + request.FileName); var len = 0L; if (fileinofo.Exists) { len = fileinofo.Length; } Message response = new Message(MessageType.SENDFILRESENDCHECK); response.MessageHeader.TransactionID = message.MessageHeader.TransactionID; response.SetMessageBody(new SendFileCheckResponseMessage { FileLength = len, FileName = request.FileName }); SendMessage(response, session.EndPoint); } }
static void Main2(string[] args) { var request = new LJC.FrameWork.Comm.HttpRequestEx(); request.SupportCompression = true; var response = request.DoRequest("http://jingzhi.funds.hexun.com/jz/", null); List <string> list = new List <string>(); var tpp = list.GetType(); Dictionary <int, string> dics = new Dictionary <int, string>(); dics.Add(1, "ljc"); dics.Add(2, "cc"); Type tp = dics.GetType(); TestClass test = new TestClass(); test.col1 = 1234; test.DateCol = DateTime.Now; test.LongCol = 234456788; test.flag = EntityBufTypeFlag.TestFlag | EntityBufTypeFlag.ArrayFlag; test.flags = new EntityBufTypeFlag[] { EntityBufTypeFlag.ArrayFlag, EntityBufTypeFlag.TestFlag, EntityBufTypeFlag.ThreeFlag, }; test.IntArray = new int[] { 1000, 200, 122 }; test.List = new List <Test2Class>(); test.List.Add(new Test2Class { Boo = false, xx = 1, }); test.List.Add(new Test2Class { Boo = true, xx = 22, }); test.List.Add(new Test2Class { Boo = false, xx = 1200, }); test.Dic = new Dictionary <int, string>(); test.Dic.Add(1, "xxxx"); test.Dic.Add(2, "haha"); test.Dic2 = new Dictionary <int, Test2Class>(); test.Dic2.Add(1, new Test2Class { Boo = true, xx = 2 }); test.Dic2.Add(2, new Test2Class { Boo = true, xx = 3 }); var dic3item = new Dictionary <string, Test2Class>(); dic3item.Add("1", new Test2Class { Boo = true, xx = 10998 }); dic3item.Add("2", new Test2Class { Boo = false, xx = 2558, }); test.Dic3 = new Dictionary <int, Dictionary <string, Test2Class> >(); test.Dic3.Add(1, dic3item); test.Dic3.Add(2, dic3item); test.DateColArray = new DateTime[] { new DateTime(1990, 1, 1, 0, 1, 1), new DateTime(1991, 1, 1, 0, 1, 1), new DateTime(1992, 1, 1, 0, 1, 1), new DateTime(1993, 1, 1, 0, 1, 1), }; test.BoolArray = new bool[] { false, false, true, true, false, true }; test.Test2 = new Test2Class { xx = 1111, Boo = true, }; test.longArray = new long[] { 1, 2, 3, 45 }; test.ListTest2 = new Test2Class[] { new Test2Class { xx = 1223, Boo = true, }, new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, }, new Test2Class { xx = 998, Boo = false, } , new Test2Class { xx = 998, Boo = false, } }; var innerDic = new Dictionary <int, string>(); innerDic.Add(1, "ljc"); innerDic.Add(2, "李大大象"); test.DicArray = new Dictionary <int, string>[] { innerDic }; System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch(); sp.Restart(); long m1 = GC.GetTotalMemory(true); for (int i = 0; i < 1; i++) { string jsonstr = test.ToJson(); if (i == 0) { int len = Encoding.UTF8.GetBytes(jsonstr).Length; Console.WriteLine("JSON序列化包的大小:" + len + "字节"); } var fromjson = (TestClass)LJC.FrameWork.Comm.JsonHelper.JsonToEntity <TestClass>(jsonstr); } long m2 = GC.GetTotalMemory(true); sp.Stop(); Console.WriteLine("JSON序列化反序列化总共费时:" + sp.ElapsedMilliseconds); Console.WriteLine("共用内存:" + (m2 - m1).ToString()); sp.Restart(); long m3 = GC.GetTotalMemory(true); for (int i = 0; i < 100; i++) { var data = EntityBufCore.Serialize(test); if (i == 0) { Console.WriteLine("二进制序列化包的大小:" + data.Length + "字节"); } //MemoryStream ms2 = new MemoryStream(ms.GetBuffer()); //LJC.FrameWork.EntityBuf.MemoryStreamReader reader = new MemoryStreamReader(new BinaryReader(ms2)); object o = EntityBufCore.DeSerialize <TestClass>(data); } long m4 = GC.GetTotalMemory(true); sp.Stop(); Console.WriteLine("二进制序列化反序列化总共费时:" + sp.ElapsedMilliseconds); Console.WriteLine("共用内存:" + (m4 - m3).ToString()); sp.Restart(); long m5 = GC.GetTotalMemory(true); for (int i = 0; i < 0; i++) { string xml = LJC.FrameWork.Comm.SerializerHelper.SerializerToXML(test); if (i == 0) { int len = Encoding.UTF8.GetBytes(xml).Length; Console.WriteLine("xml序列化包大小:" + len + "字节"); } var xmlOjb = LJC.FrameWork.Comm.SerializerHelper.DeserializerXML <TestClass>(xml); } long m6 = GC.GetTotalMemory(true); sp.Stop(); Console.WriteLine("xml序列化反序列化总共费时:" + sp.ElapsedMilliseconds); Console.WriteLine("共用内存:" + (m6 - m5).ToString()); //byte bt = (byte)EntityBufTypeFlag.ThreeFlag; //PropertyInfo[] props = typeof(TestClass).GetProperties(); //foreach (PropertyInfo prop in props) //{ // string s = prop.ReflectedType.Name; //} //var result= LJC.FrameWork.Comm.CommFun.GetQuickDataBaseAttr<TestClass>(); //string filename=@"E:\程序\投资机器人(广发证券真实交易版)\ATrade_gx\ATUI2.0\ATradeUI2.0\bin\Debug\gfaccount\x.png"; //LJC.FrameWork.Comm.ImageHelper.SaveImage(null, ref filename, false); //string s=TT(p => p.col1); //var josn1 = "{\"error_info\":\"验证码输入不正确!\",\"success\":false}"; //var ss= JsonHelper.FormJson(josn1).EvalJson("error_info"); //var josn2 = "{\"total\":1,\"data\":[{\"pre_interest_tax\":\"0\",\"pre_fine\":\"0\",\"money_type\":\"0\",\"fetch_balance\":\"28562.30\",\"current_balance\":\"28562.30\",\"real_sell_balance\":\"0\",\"integral_balance\":\"1066933.58\",\"market_value\":\"5751.00\",\"correct_balance\":\"0\",\"money_type_dict\":\"人民币\",\"foregift_balance\":\"0\",\"fetch_balance_old\":\"0\",\"mortgage_balance\":\"0\",\"frozen_balance\":\"0\",\"pre_interest\":\"10.37\",\"interest\":\"0\",\"asset_balance\":\"34313.30\",\"enable_balance\":\"28562.30\",\"unfrozen_balance\":\"0\",\"fine_integral\":\"0\",\"fetch_cash\":\"28562.30\",\"opfund_market_value\":\"0\",\"real_buy_balance\":\"0\",\"entrust_buy_balance\":\"0\",\"rate_kind\":\"0\",\"fund_balance\":\"28562.30\",\"begin_balance\":\"28562.30\"}],\"success\":true}"; //var dj=JsonHelper.DynamicJson(josn2); //int total = dj.total; //var current_balance = dj.data[0]["current_balance"]; //var josn3 = "[{name:\"ljc\",age:29},{name:\"chenghong\",age:22}]"; //var dj3 = JsonHelper.DynamicJson(josn3); //var age2 = dj3[1]["age"]; }
private void OnSocket(object obj) { Socket socket = (Socket)obj; socket.NoDelay = true; socket.ReceiveBufferSize = 32000; socket.SendBufferSize = 32000; IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint; Session appSocket = new Session(); appSocket.IPAddress = endPoint.Address.ToString(); appSocket.IsValid = true; appSocket.SessionID = SocketApplicationComm.GetSeqNum(); appSocket.Socket = socket; while (appSocket.IsValid && appSocket.Socket.Connected) { try { byte[] buff4 = new byte[4]; int count = socket.Receive(buff4); if (count != 4) { throw new SessionAbortException("接收数据出错。"); } int dataLen = BitConverter.ToInt32(buff4, 0); if (dataLen > MaxPackageLength) { throw new Exception("超过了最大字节数:" + MaxPackageLength); } MemoryStream ms = new MemoryStream(); int readLen = 0; byte[] reciveBuffer = new byte[1024]; while (readLen < dataLen) { count = socket.Receive(reciveBuffer, Math.Min(dataLen - readLen, reciveBuffer.Length), SocketFlags.None); readLen += count; ms.Write(reciveBuffer, 0, count); } var buffer = ms.ToArray(); ms.Close(); //搞成异步的 new Action <byte[], Session>((b, s) => { Message message = EntityBufCore.DeSerialize <Message>(b); FormApp(message, s); }).BeginInvoke(buffer, appSocket, null, null); } catch (SessionAbortException exp) { SocketApplicationComm.Debug(exp.Message); break; } catch (SocketException exp) { SocketApplicationComm.Debug(exp.Message); break; } catch (Exception exp) { SocketApplicationComm.Debug(exp.Message); OnError(exp); } } socket.Close(); SocketApplicationComm.Debug(string.Format("服务器关闭套接字:{0}", appSocket.SessionID)); }
void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e) { e.Completed -= SocketAsyncEventArgs_Completed; var args = e as IOCPSocketAsyncEventArgs; if (args.BytesTransferred == 0 || args.SocketError != SocketError.Success) { if (SocketApplication.SocketApplicationEnvironment.TraceSocketDataBag) { LogManager.LogHelper.Instance.Debug(e.AcceptSocket.Handle + "异常断开:" + args.SocketError); } RemoveSession(args); return; } else { bool hasdataerror = false; try { #region 数据逻辑 if (!args.IsReadPackLen) { if (args.BytesTransferred != 4) { throw new Exception("读取长度失败"); } var offset = args.BufferIndex == -1 ? 0 : _bufferpoll.GetOffset(args.BufferIndex); var dataLen = BitConverter.ToInt32(e.Buffer, offset); if (SocketApplication.SocketApplicationEnvironment.TraceSocketDataBag) { LogManager.LogHelper.Instance.Debug(e.AcceptSocket.Handle + "准备接收数据:长度" + dataLen, null); } if (dataLen > MaxPackageLength || dataLen <= 0) { throw new SocketSessionDataException(string.Format("数据异常,长度:" + dataLen)); } else { args.IsReadPackLen = true; //byte[] readbuffer = new byte[dataLen]; args.BufferLen = dataLen; args.BufferRev = 0; //args.SetBuffer(readbuffer, 0, dataLen); SetBuffer(args, 0, dataLen); } } else { if (SocketApplication.SocketApplicationEnvironment.TraceSocketDataBag) { var offset1 = (args.BufferLen == args.Buffer.Length) ? 0 : _bufferpoll.GetOffset(args.BufferIndex); var bytes = args.Buffer.Skip(offset1 + args.BufferRev).Take(args.BytesTransferred).ToArray(); //if (args.BytesTransferred < args.BufferLen) { LogManager.LogHelper.Instance.Debug(string.Format(e.AcceptSocket.Handle + "接收数据{0}/{1}/{2},{3}", args.BufferLen, args.BufferRev, args.BytesTransferred, Convert.ToBase64String(bytes)), null); } } args.BufferRev += args.BytesTransferred; Exception messageError = null; if (args.BufferRev == args.BufferLen) { byte[] bt = null; var offset = args.BufferIndex == -1 ? 0 : _bufferpoll.GetOffset(args.BufferIndex); //校验 var crc32 = BitConverter.ToInt32(args.Buffer, offset); var calcrc32 = LJC.FrameWork.Comm.HashEncrypt.GetCRC32(args.Buffer, offset + 4, args.BufferLen - 4); if (calcrc32 == crc32) { bt = new byte[args.BufferLen - 4]; for (int i = 4; i < args.BufferLen; i++) { bt[i - 4] = args.Buffer[offset + i]; } ThreadPool.QueueUserWorkItem(new WaitCallback((buf) => { Session connSession = null; try { Message message = null; if (_connectSocketDic.TryGetValue(args.UserToken.ToString(), out connSession)) { if (!string.IsNullOrWhiteSpace(connSession.EncryKey)) { try { bt = AesEncryHelper.AesDecrypt(bt, connSession.EncryKey); } catch (Exception ex) { throw new SocketApplicationException("解密失败", ex); } } try { message = EntityBufCore.DeSerialize <Message>(bt); } catch (Exception ex) { messageError = ex; } connSession.LastSessionTime = DateTime.Now; connSession.BytesRev += bt.Length; if (messageError == null) { //如果是协商加密的 if (message.IsMessage(MessageType.NEGOTIATIONENCRYR)) { var nmsg = message.GetMessageBody <NegotiationEncryMessage>(); if (string.IsNullOrWhiteSpace(nmsg.PublicKey)) { throw new SocketApplicationException("公钥错误"); } var encrykey = connSession.EncryKey; if (string.IsNullOrWhiteSpace(encrykey)) { encrykey = Guid.NewGuid().ToString("N"); Console.WriteLine("发送加密串:" + encrykey); var rep = new Message(MessageType.NEGOTIATIONENCRYR); rep.SetMessageBody(nmsg); nmsg.EncryKey = Convert.ToBase64String(RsaEncryHelper.RsaEncrypt(Encoding.ASCII.GetBytes(encrykey), nmsg.PublicKey));; connSession.SendMessage(rep); connSession.EncryKey = encrykey; } else { throw new SocketApplicationException("不允许多次协商密钥"); } } else { FromApp(message, connSession); } } else { OnError(messageError); } } else { OnError(new Exception("取会话失败,args.UserToken=" + args.UserToken)); } } catch (SocketApplicationException ex) { if (connSession != null) { connSession.Close(); } ex.Data.Add("SessionID", connSession.SessionID); OnError(ex); } }), bt); } else { messageError = new Exception("检查校验码出错"); messageError.Data.Add("crc32", crc32); messageError.Data.Add("calcrc32", calcrc32); messageError.Data.Add("data", bt == null ? "" : Convert.ToBase64String(bt)); //LogManager.LogHelper.Instance.Error("接收数据出错", messageError); Session connSession; if (_connectSocketDic.TryGetValue(args.UserToken.ToString(), out connSession)) { connSession.LastSessionTime = DateTime.Now; connSession.BytesRev += args.BufferRev; OnError(messageError); } else { OnError(new Exception("取会话失败,args.UserToken=" + args.UserToken)); } } args.IsReadPackLen = false; //args.SetBuffer(_bufferpoll.Buffer, _bufferpoll.GetOffset(args.BufferIndex), 4); SetBuffer(args, 0, 4); } else { SetBuffer(args, args.BufferRev, args.BufferLen - args.BufferRev); LogManager.LogHelper.Instance.Debug("e.SetBuffer:" + (args.BufferRev) + ",len:" + (args.BufferLen - args.BufferRev), null); } } #endregion } catch (SocketSessionDataException ex) { RemoveSession(args); hasdataerror = true; OnError(ex); } catch (Exception ex) { OnError(ex); } finally { if (!hasdataerror) { e.Completed += SocketAsyncEventArgs_Completed; if (!e.AcceptSocket.ReceiveAsync(e)) { LogManager.LogHelper.Instance.Debug(e.AcceptSocket.Handle + "同步完成,手动处理", null); SocketAsyncEventArgs_Completed(null, e); } } } } }
private void ReadSocketList() { var list = _connectSocketDic.Select(p => p.Value).ToList(); var readlist = list.Select(p => p.Socket).ToList(); var errlist = new List <Socket>(); if (readlist.Count > 0) { int taskcount = (int)Math.Ceiling(readlist.Count / 1000.0); taskcount = Math.Max(taskcount, 60); taskcount = Math.Min(readlist.Count, taskcount); TaskHelper.RunTask <Socket>(readlist, taskcount, (o) => { var sublist = ((List <Socket>)o); Socket.Select(sublist, null, null, 1); Session s = null; int delcount = 0; foreach (var item in sublist) { try { _connectSocketDic.TryGetValue(item.Handle.ToInt64().ToString(), out s); if (!(s.IsValid && s.Socket.Connected)) { lock (errlist) { errlist.Add(item); } continue; } delcount = 0; while (item.Poll(1, SelectMode.SelectRead) && delcount < 100) { byte[] buff4 = new byte[4]; int count = item.Receive(buff4); int dataLen = BitConverter.ToInt32(buff4, 0); if (dataLen > MaxPackageLength) { throw new Exception("超过了最大字节数:" + MaxPackageLength); } count = item.Receive(buff4); var crc32 = BitConverter.ToInt32(buff4, 0); MemoryStream ms = new MemoryStream(); dataLen -= 4; int readLen = 0; byte[] reciveBuffer = new byte[1024]; while (readLen < dataLen) { count = item.Receive(reciveBuffer, Math.Min(dataLen - readLen, reciveBuffer.Length), SocketFlags.None); readLen += count; ms.Write(reciveBuffer, 0, count); } var buffer = ms.ToArray(); ms.Close(); var calcrc32 = LJC.FrameWork.Comm.HashEncrypt.GetCRC32(buffer, 0); if (crc32 != calcrc32) { throw new Exception("数据校验错误"); } ThreadPool.QueueUserWorkItem(new WaitCallback((buf) => { Message message = EntityBufCore.DeSerialize <Message>((byte[])buf); FormApp(message, _connectSocketDic[item.Handle.ToInt64().ToString()]); }), buffer); delcount += 1; } } catch (Exception ex) { OnError(ex); } } ; }); } Session removesession = null; foreach (var item in errlist) { if (_connectSocketDic.TryRemove(item.Handle.ToInt64().ToString(), out removesession)) { item.Close(); } } }