/// <summary> /// 发送请求数据包的方法 /// </summary> /// <param name="fastMsg"></param> /// <param name="funcId"></param> /// <returns></returns> private Task SendRequsetPackage(LDFastMessageAdapter fastMsg, string funcId) { Task tsk = Task.Run(() => { sendConnectionAdapter.AsyncSend(funcId, fastMsg, 60000); fastMsg.FreeMsg(); }); return(tsk); }
/// <summary> /// 发送广播数据包的方法 /// </summary> /// <param name="fastMsg"></param> /// <param name="funcId"></param> /// <returns></returns> private Task <int> SendPubTopicsPackage(LDFastMessageAdapter fastMsg, string funcId) { int result = -1; Task <int> tsk = Task <int> .Run(() => { result = sendConnectionAdapter.PubTopics(funcId, fastMsg); fastMsg.FreeMsg(); return(result); }); return(tsk); }
/// <summary> /// 发送数据并且绘制正弦曲线 /// </summary> private async void DrawSin() { try { int Zoom = 15; //放大倍数 Point center = new Point(0, pbShow.Height / 2); //原点 float x1 = (float)(0 * Math.PI * Zoom / 180 + center.X); float y1 = (float)(Math.Sin(0 * Math.PI / 180) * 11 * Zoom + center.Y); grap.DrawLine(Pens.Black, 0, center.Y, pbShow.Width, center.Y); //x坐标轴 grap.DrawLine(Pens.Black, center.X, 0, center.X, pbShow.Height); //y坐标轴 LDFastMessageAdapter fastMsg = new LDFastMessageAdapter("pubL.16.5", 0); StockLevelRealTimeData stockFiled = new StockLevelRealTimeData(); for (double i = 1; i < 360 * 4; i++) //角 { if (isPause) { waitHandle.WaitOne(); } float x2 = (float)(i * Math.PI * Zoom / 180 + center.X); float y2 = (float)Math.Sin(i * Math.PI / 180) * (-1) * 11 * Zoom + center.Y; grap.DrawLine(Pens.Red, x1, y1, x2, y2); grap.Save(); this.pbShow.Invoke(new Action(() => { pbShow.Image = bmp; })); #region 针对每个券码发送一个生成并发送一个数据包 int rows = LoadStockInfo.excelData.GetLength(0); for (int j = 1; j < rows; j++) { //券码 string stockNo = LoadStockInfo.excelData[j, 1].ToString(); char[] stockNos = stockNo.ToCharArray(); if (stockNos.Length < 5 || stockNos.Length > 6) { continue; } if (stockNos.Length < 6) { var tempStocks = stockNos.ToList(); tempStocks.Add('\0'); stockNos = tempStocks.ToArray(); } //涨停价 double upPrice = Convert.ToDouble(LoadStockInfo.excelData[j, 4]); //跌停价 double downPrice = Convert.ToDouble(LoadStockInfo.excelData[j, 5]); //初始价格 double price0 = (upPrice + downPrice) / 2.00; //递增/递减价格 double price1 = (upPrice - price0) * Math.Sin(i * Math.PI / 180) + price0; double price2 = (upPrice - price0) * Math.Sin((i + 1) * Math.PI / 180) + price0; double price3 = (upPrice - price0) * Math.Sin((i + 2) * Math.PI / 180) + price0; double price4 = (upPrice - price0) * Math.Sin((i + 3) * Math.PI / 180) + price0; double price5 = (upPrice - price0) * Math.Sin((i + 4) * Math.PI / 180) + price0; fastMsg.SetInt32(LDBizTag.LDBIZ_EXCH_NO_INT, 1); fastMsg.SetString(LDBizTag.LDBIZ_STOCK_CODE_STR, stockNo); //开始组装数据包 int tmpValue = 1000; int tmpValue0 = 100; stockFiled.PriceUnit = tmpValue; stockFiled.UpPrice = (int)(upPrice * tmpValue); stockFiled.DownPrice = (int)(downPrice * tmpValue); stockFiled.FiveDayVol = 0; stockFiled.OpenPrice = (int)(price0 * tmpValue); stockFiled.PrevClose = (int)(price0 * tmpValue);; stockFiled.BuyPrice1 = (int)(price1 * tmpValue); stockFiled.BuyPrice2 = (int)(price2 * tmpValue); stockFiled.BuyPrice3 = (int)(price3 * tmpValue); stockFiled.BuyPrice4 = (int)(price4 * tmpValue); stockFiled.BuyPrice5 = (int)(price5 * tmpValue); stockFiled.BuyCount1 = (uint)(tmpValue0 * i); stockFiled.BuyCount2 = (uint)(tmpValue0 * i * 2); stockFiled.BuyCount3 = (uint)(tmpValue0 * i * 3); stockFiled.BuyCount4 = (uint)(tmpValue0 * i * 4); stockFiled.BuyCount5 = (uint)(tmpValue0 * i * 5); stockFiled.SellPrice1 = (int)(price1 * tmpValue); stockFiled.SellPrice2 = (int)(price2 * tmpValue); stockFiled.SellPrice3 = (int)(price3 * tmpValue); stockFiled.SellPrice4 = (int)(price4 * tmpValue); stockFiled.SellPrice5 = (int)(price5 * tmpValue); stockFiled.SellCount1 = (uint)(tmpValue0 * i); stockFiled.SellCount2 = (uint)(tmpValue0 * i * 2); stockFiled.SellCount3 = (uint)(tmpValue0 * i * 3); stockFiled.SellCount4 = (uint)(tmpValue0 * i * 4); stockFiled.SellCount5 = (uint)(tmpValue0 * i * 5); stockFiled.AvgPrice = (int)(price1 * tmpValue) * (uint)(tmpValue0 * i) + (int)(price2 * tmpValue) * (uint)(tmpValue0 * i * 2) + (int)(price3 * tmpValue) * (uint)(tmpValue0 * i * 3) + (int)(price4 * tmpValue) * (uint)(tmpValue0 * i * 4) + (int)(price5 * tmpValue) * (uint)(tmpValue0 * i * 5); stockFiled.MaxPrice = (int)(price5 * tmpValue); stockFiled.MinPrice = (int)(price1 * tmpValue); stockFiled.NewPrice = (int)(price3 * tmpValue); stockFiled.HandNum = 100; stockFiled.CodeType = 4361; stockFiled.Decimal = 3; stockFiled.StockCode = stockNos; stockFiled.Total = (uint)(tmpValue0 * i * 10); //将数据包转化成非托管类型 IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(stockFiled)); Marshal.StructureToPtr(stockFiled, ptr, false); fastMsg.SetRawData(LDBizTag.LDBIZ_QUOT_PRICE_INFO_STR, ptr, Marshal.SizeOf(stockFiled)); //制造阻塞,确保数据包发送之后才进行内存回收 int result = await SendPackage(fastMsg); fastMsg.FreeMsg(); Marshal.FreeHGlobal(ptr); Thread.Sleep(TimeSpan.FromMilliseconds(delay)); } #endregion x1 = x2; y1 = y2; } this.btnStart.Invoke(new Action(() => { btnStart.Enabled = true; })); } catch (Exception error) { Log.WriteLog(error.Message); MessageBox.Show(error.StackTrace + "\r\n" + error.Message); } }
/// <summary> /// 发送请求数据包的方法 /// </summary> /// <param name="fun">已经构建好的请求应答包</param> /// <param name="defaultTable">对应defaultvalue.xlsx文件,取默认值用的</param> private unsafe void SendFastMsgFun(BizFunction fun, DataTable defaultTable) { LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(fun.FunctonId, 0); LDRecordAdapter lpRecord = fastmsg.GetBizBodyRecord(); //获取字段总数量 int iFieldCount = lpRecord.GetFieldCount(); int iIndex = 0; for (iIndex = 0; iIndex < iFieldCount; iIndex++) { //取得字段类型 int fieldtype = lpRecord.GetFieldType(iIndex); //取得字段名称 string fieldName = lpRecord.GetFieldNamebyIndex(iIndex); BizRequestField bizField = fun.ReqFields.FirstOrDefault(o => o.FieldName.Equals(fieldName)); String fieldValue = ""; if (bizField != null) { fieldValue = bizField.FieldValue; //取得入参的值 } if (string.IsNullOrEmpty(fieldValue)) //如果没有手动赋值,则去默认值 { fieldValue = UtilTool.GetDefaultValue(defaultTable, fieldName); } if ("func_code".Equals(fieldName)) //如果字段名称是func_code,则把功能号作为值赋给字段 { fieldValue = fun.FunctonId; } UtilTool.SetFastMsgValue(fastmsg, fieldtype, fieldValue, iIndex); } //应答包 LDFastMessageAdapter outFast = null; int nRet = (int)ConnectionManager.Instance.CurConnection.Connect.SendAndReceive(fun.FunctonId, fastmsg, ref outFast, 5000); fastmsg.FreeMsg(); /**********************************开始对应答包进行处理**************************************/ if (nRet < 0) { LogHelper.Logger.Error(fun.FunctonId + "发送失败,错误号=" + nRet); PrintHelper.Print.AppendLine(fun.FunctonId + "发送失败,错误号=" + nRet); } if (nRet >= 0 && outFast.Record != null) { int iErrorNo = outFast.GetInt32(LDSdkTag.LDTAG_ERRORNO); if (iErrorNo != 0) { LogHelper.Logger.Error("SystemErrorInfo=" + outFast.GetString(LDSdkTag.LDTAG_ERRORINFO)); } else { //将回归脚本的应答包信息写入文件 //string savePath = Environment.CurrentDirectory + @"\RegressionTestResult.txt";//文件保存路径 //LogAnswerPackageInfo.OutPutResult(outFast, savePath); if (fun.AnswerFlag) { //获取应答包包体数据 LDRecordAdapter lpOutRecord = outFast.GetBizBodyRecord(); //获取应答包字段总数 int iAnswerFieldCount = lpOutRecord.GetFieldCount(); //遍历获取应答包字段的 出参=值 信息,并塞入到对应的请求应答包里面去 BizFunction fun int iAnswerIndex = 0; for (iAnswerIndex = 0; iAnswerIndex < iAnswerFieldCount; iAnswerIndex++) { //获取出参字段名 string fieldName = lpOutRecord.GetFieldNamebyIndex(iAnswerIndex); //获取出参字段类型 int fieldType = lpOutRecord.GetFieldType(iAnswerIndex); //只把会用到的字段塞入 BizAnswerField bizField = fun.Answer.RspFields.FirstOrDefault(o => o.FieldName.Equals(fieldName)); if (bizField != null) { bizField.FieldValue = UtilTool.GetFastMsgValue(outFast, fieldType, iAnswerIndex); bizField.FieldType = fieldType; } } } } outFast.FreeMsg(); } }
/// <summary> /// 发送压力测试的请求包 /// </summary> /// <param name="file"></param> /// <param name="result"></param> private void SendFastMsgReq(CaseFileData file, out string result) { try { foreach (CaseFunction funitem in file.Functions) { int nSendTimes = 0; do { bool bNeedWait = (file.SendCount - file.RecCount) >= file.UpStage; if (bNeedWait) { file.ResetEvent.Reset(); if (!file.ResetEvent.WaitOne(10000)) { file.SendCount = file.RecCount; //每秒钟判断一次是否达到积压上限 continue; } } nSendTimes++; #region 发送包 LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(funitem.FunID, funitem.FunType); //读取储存默认值的Excel文档,给未复制的参数赋予默认值 foreach (var filedItem in funitem.Fileds) { string FiledValue = filedItem.FiledValue; int filedType = filedItem.FiledType; string filedName = filedItem.FiledName; FiledValue = GetParamValue(funitem, filedItem); //如果获取参数值失败,直接退出 if (FiledValue == "error") { result = "error"; return; } if (string.IsNullOrEmpty(FiledValue)) { //没有默认值,取默认值 if (!filedItem.HaveDefaultValue) { FiledValue = GetDefaultValue(filedItem.FiledName, FiledValue); filedItem.DefaultValue = FiledValue; filedItem.HaveDefaultValue = true; } FiledValue = filedItem.DefaultValue; } UtilTool.SetFastMsgValueById(fastmsg, filedType, FiledValue, filedItem.FiledTag); } int sendId = Interlocked.Increment(ref LastSendId); fastmsg.SetInt32(LDBizTagDefine.LDSdkTag.LDTAG_PACKETID, sendId); //赋值完毕,异步发送数据包 lock (ReqLock) { ReqAllList.Add(new ReqDTO() { SendID = sendId, CaseData = file }); } int nRet = (int)ConnectionManager.Instance.CurConnection.Connect.AsyncSend(funitem.FunID, fastmsg, 5000); if (nRet > 0) { Interlocked.Increment(ref file.SendCount); Interlocked.Increment(ref file.SendOkCount); } else { Interlocked.Increment(ref file.SendFailCount); } fastmsg.FreeMsg(); #endregion }while (funitem.SendTimes > nSendTimes); } result = "OK"; } catch (Exception error) { this.Dispatcher.Invoke(() => { MessageBox.Show($"{error.Message} \r\n {error.StackTrace}"); }); result = "error"; } }
/// <summary> /// 加载案例数据 /// </summary> /// <param name="filePath"></param> /// <param name="funList"></param> /// <returns></returns> public CaseFileData LoadCaseData(String filePath, List <CaseFunction> funList) { CaseFileData datas = new CaseFileData(); try { if (!File.Exists(filePath)) { return(datas); } datas.FilePath = @filePath; XElement rootXML = XDocument.Load(filePath).Element("bizmsgs"); var funsXml = rootXML.Elements("function"); foreach (var item in funsXml) { string functionid = item.Attribute("functionid").Value; string packettype = item.Attribute("packettype").Value; var CheckFun = funList.FirstOrDefault(o => o.Check == 1 && o.FunID == functionid); if (packettype.Equals("0") && CheckFun != null) { string functionname = item.Attribute("functionname").Value; CaseFunction fun = new CaseFunction() { FunID = functionid, FunType = 0, Check = 1, FunName = functionname }; //发送次数 if (item.Attribute("times") != null) { string sendTimes = item.Attribute("times").Value; int nSendTimes = 1; int.TryParse(sendTimes, out nSendTimes); fun.SendTimes = nSendTimes; } datas.Functions.Add(fun); var filedsXml = item.Elements("field"); LDsdkDefineEx.LDFastMessageAdapter fastmsg = new LDFastMessageAdapter(functionid, 0); LDRecordAdapter lpRecord = fastmsg.GetBizBodyRecord(); int iIndex = 0; foreach (var filedItem in filedsXml) { string fieldid = filedItem.Attribute("fieldid").Value; string fieldname = filedItem.Attribute("fieldname").Value; int filedtype = lpRecord.GetFieldType(iIndex); PARAMTYPE paramtype = PARAMTYPE.emFile; string value = ""; if (filedItem.Attribute("value") != null) { value = filedItem.Attribute("value").Value; } if (filedItem.Attribute("paramtype") != null) { string strparamtype = filedItem.Attribute("paramtype").Value; if ("file".Equals(strparamtype)) { paramtype = PARAMTYPE.emFile; } } CaseFiled filed = new CaseFiled() { FiledTag = int.Parse(fieldid), FiledName = fieldname, FiledValue = value, FiledType = filedtype, FiledIndex = iIndex, ParamType = paramtype }; var fileElemt = filedItem.Element("file"); if (fileElemt != null && paramtype == PARAMTYPE.emFile) { filed.ColumnName = fieldname; if (fileElemt.Attribute("columnname") != null) { filed.ColumnName = fileElemt.Attribute("columnname").Value; } if (fileElemt.Attribute("filename") != null) { filed.FileName = fileElemt.Attribute("filename").Value; CSVFile csvFile = null; if (File.Exists(filed.FileName) && !fun.AllCsvFile.TryGetValue(filed.FileName, out csvFile)) { var data = CSVFileHelper.OpenCSV(filed.FileName); if (data != null) { csvFile = new CSVFile(); csvFile.FileName = filed.FiledName; csvFile.Table = data; fun.AllCsvFile.Add(filed.FileName, csvFile); } } if (csvFile != null && string.IsNullOrWhiteSpace(csvFile.DefaultFieldName)) { csvFile.DefaultFieldName = fieldname; } } filed.SelectRow = VALUETYPE.emSameLine; if (fileElemt.Attribute("selectrow") != null) { try { string SelectRow = fileElemt.Attribute("selectrow").Value; if ("sequence".Equals(SelectRow)) { filed.SelectRow = VALUETYPE.emSequence; } else if (new Regex("same_line").Match(SelectRow).Success) { filed.SameLineColumn = SelectRow.Split('[')[1].Split(']')[0]; filed.SelectRow = VALUETYPE.emSameLine; } else if ("random".Equals(SelectRow)) { //默认("random".Equals(SelectRow)) filed.SelectRow = VALUETYPE.emRandom; } } catch (Exception) { //throw; } } } fun.Fileds.Add(filed); iIndex++; } fastmsg.FreeMsg(); } } return(datas); } catch (Exception error) { this.Dispatcher.Invoke(() => { MessageBox.Show($"{error.Message} \r\n {error.StackTrace}"); }); return(datas); } }
/// <summary> /// 死循环处理队列里的应答包 /// </summary> private void DealRespPackage() { Task.Run( () => { while (true) { RespDataPackageModel RDP = new RespDataPackageModel(); if (RespDataPackageModel.DataQueue.TryDequeue(out RDP)) { Task.Run( () => { int hSend = RDP.hSend; LDFastMessageAdapter lpFastMsg = RDP.lpFastMsg; DateTime timeStamp = DateTime.Now; ReqDTO req = null; lock (ReqLock) { req = ReqAllList.FirstOrDefault(o => o.SendID == hSend); ReqAllList.Remove(req); } if (req != null && lpFastMsg != null) { Interlocked.Increment(ref req.CaseData.RecCount); //递增应答数量 if (req.CaseData.SendCount - req.CaseData.RecCount <= req.CaseData.DownStage) { req.CaseData.ResetEvent.Set(); } //功能号 string strFunCode = lpFastMsg.GetString(LDSdkTag.LDTAG_FUNCID); /***********************************郑建翔新加部分,用于计算应答频率***************************************/ lock (lockFlag) { //如果集合中不存这个功能号则添加 if (ReplyRateInfos.Count(i => i.functionId == strFunCode) == 0) { DateTime startTime = DateTime.Now; this.Dispatcher.Invoke(() => ReplyRateInfos.Add(new ReplyRateModel(strFunCode, startTime))); /*****************************接收到每个功能号的第一条应答时,保存应答信息**************************/ //文件保存路径 string savePath = Environment.CurrentDirectory + @"\ScriptOutPut.txt"; LogAnswerPackageInfo.OutPutResult(lpFastMsg, savePath); } else { //如果集合中已经存在这个功能号,开始更新并计算数据 ReplyRateModel replyInfo = ReplyRateInfos.FirstOrDefault(i => i.functionId == strFunCode); replyInfo.timeStamp = timeStamp; replyInfo.replyCount++; } } /*******************************************修改结束*********************************************************/ int iErrorNo = lpFastMsg.GetInt32(LDSdkTag.LDTAG_ERRORNO); // LogHelper.Logger.Info("系统错误号:" + iErrorNo); if (iErrorNo != 0) { //如果是中间件返回的错误 // Interlocked.Increment(ref req.CaseData.RecFailCount);//递增应答失败数量 } else { string strErrorCode = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_CODE_STR); //LogHelper.Logger.Info("业务错误号:" + strErrorCode); Interlocked.Increment(ref req.CaseData.RecOkCount); //递增应答成功数量 if (!"0".Equals(strErrorCode)) { Interlocked.Increment(ref req.CaseData.RecFailCount); //递增应答失败数量 string strErrorInfo = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_INFO_STR); string strErrorPrompt = lpFastMsg.GetString(LDBizTag.LDBIZ_ERROR_PROMPT_STR); string logInfo = string.Format("功能号[{0}],errorCode[{1}],errorinfo[{2}],errorprompt[{3}]", strFunCode, strErrorCode, strErrorInfo, strErrorPrompt); LogHelper.Logger.Error(logInfo); } //else //{ // Interlocked.Increment(ref req.CaseData.RecOkCount);//递增应答成功数量 //} } } if (lpFastMsg != null) { lpFastMsg.FreeMsg(); } } ); } //else //{ // pauseFlag.WaitOne(10); //} } } ); }