首页 > 代码库 > C#模拟进行压力测试
C#模拟进行压力测试
using System;using System.Diagnostics;using System.IO;using System.Net;using System.Text;using System.Threading;using Newtonsoft.Json.Linq;namespace TestKaiPing{ class Program { private static long _totalTimeCost = 0; private static int _endedConnenctionCount = 0; private static int _failedConnectionCount = 0; private static int _connectionCount = 0; static void Main(string[] args) { var connectionCount = 100000; var requestThread = new Thread(() => StartRequest(connectionCount)) {IsBackground = true}; requestThread.Start(); Console.WriteLine("恭喜,成功完成!"); Console.ReadLine(); } private static void SendRequest() { try { var url = "http://kpsso.kpedu.com/ajaxLogin?targetService=http://221.194.113.150/dsideal_yy/html/ypt/getLoginInfo.jsp&callback=loginFormState&userName=dscsjs1&password=123456"; var r = SendRequestByGet(url); r = r.Replace("loginFormState(", "").Replace(")", ""); var o = JObject.Parse(r); var ticket = o["ticket"]; url = "http://221.194.113.150/dsideal_yy/html/ypt/getLoginInfo.jsp?ticket=" + ticket; r = SendRequestByGet(url); IncreaseSuccessConnection(); } catch (Exception) { IncreaseFailedConnection(); } } private static void Reset() { _failedConnectionCount = 0; _endedConnenctionCount = 0; _totalTimeCost = 0; } private static void IncreaseFailedConnection() { Interlocked.Increment(ref _failedConnectionCount); Console.WriteLine("失败个数:"+ _failedConnectionCount); } private static void IncreaseSuccessConnection() { Interlocked.Increment(ref _endedConnenctionCount); Console.WriteLine("成功个数:"+ _endedConnenctionCount); } private static void StartRequest(int connectionCount) { Reset(); for (var i = 0; i < connectionCount; i++) { ThreadPool.QueueUserWorkItem(u => SendRequest()); } } public static string SendRequestByGet(string uri) { string fullhtml = null; while (true) { try { var req = (HttpWebRequest)WebRequest.Create(uri); req.Method = "GET"; req.ServicePoint.ConnectionLimit = int.MaxValue; req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0"; req.KeepAlive = true; req.Timeout = 1000 * 10; var resp = (HttpWebResponse)req.GetResponse(); if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应 continue; var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8); fullhtml = sr.ReadToEnd().Trim(); resp.Close(); sr.Close(); break; } catch (WebException e) { e.StackTrace.ToString(); Trace.WriteLine(e.Message); if (true) continue; } } return fullhtml; } }}
C#模拟进行压力测试
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。