public RequestAgent(TcpClientAgent clientAgent, ServerAgent serverAgent, HttpRequest request, HttpResponse response, UrlRouteServerGroup.UrlServerInfo urlServerInfo, Routes.UrlRoute urlRoute) { mTransferEncoding = false; mRequestLength = 0; Code = 0; Server = serverAgent; Request = request; Response = response; mClientAgent = clientAgent; mClientAgent.Client.ClientError = OnSocketError; mClientAgent.Client.DataReceive = OnReveive; mBuffer = mClientAgent.Buffer; Status = RequestStatus.None; UrlServerInfo = urlServerInfo; UrlRoute = urlRoute; mStartTime = TimeWatch.GetElapsedMilliseconds(); mRequestID = request.ID; //System.Threading.Interlocked.Increment(ref RequestCount); //mHistoryRequests[mRequestID] = this; if (UrlRoute.TimeOut > 0) { TimerOutValue = mStartTime + UrlRoute.TimeOut; UrlRoute.Gateway.TimeoutFactory.Add(this); } mProxyStream = new PipeStream(UrlRoute.Gateway.ProxyBufferPool); }
public bool ValidateRPS() { lock (this) { long now = TimeWatch.GetElapsedMilliseconds(); ActiveTime = now; if (mEnbaledTime > now) { return(false); } if (mServer.Options.IPRpsLimit == 0) { return(true); } if (now - mLastTime >= 1000) { mLastTime = now; mRPS = 0; return(true); } else { mRPS++; bool result = mRPS < mServer.Options.IPRpsLimit; if (!result) { mEnbaledTime = mServer.Options.IPRpsLimitDisableTime + now; } return(result); } } }
private void OnTimeOut(object state) { mTimer.Change(-1, -1); try { for (int i = 0; i < awaiterManager.AwaiterTables.Count; i++) { var items = awaiterManager.AwaiterTables[i].TimeOut(TimeWatch.GetElapsedMilliseconds()); if (items.Count > 0) { for (int k = 0; k < items.Count; k++) { ThrowBlockException(items[k].ID, $"{items[k].ID} process timeout!"); } } } } catch (Exception e_) { OnError(null, TIMEOUT_PROCESS_ERROR, "TimeOut handler error", e_); } finally { mTimer.Change(1000, 1000); } }
private void OnCompleted() { if (System.Threading.Interlocked.CompareExchange(ref mCompletedStatus, 1, 0) == 0) { Time = TimeWatch.GetElapsedMilliseconds() - mStartTime; mClient.Client.ClientError = null; mClient.Client.DataReceive = null; try { taskCompletionSource.SetResult(this); } finally { if (mClient.Client.IsConnected) { PipeStream pipeStream = mClient.Client.Stream.ToPipeStream(); if (pipeStream.Length > 0) { pipeStream.ReadFree((int)pipeStream.Length); } } } } }
public async void Ping() { if (System.Threading.Interlocked.CompareExchange(ref mPingStatus, 1, 0) == 0) { if (TcpClient.IsConnected) { try { RPCPacket request = new RPCPacket(); request.Url = "/__System/Ping"; var response = await XRPCClient.SendWait(request, TcpClient, null); PingTime = TimeWatch.GetElapsedMilliseconds(); } catch (Exception e_) { } finally { if (TimeOut(XRPCClient.PingTimeout * 1000)) { TcpClient.DisConnect(); bool isnew; TcpClient.Connect(out isnew); } } } else { PingTime = TimeWatch.GetElapsedMilliseconds(); } System.Threading.Interlocked.Exchange(ref mPingStatus, 0); } }
public Request(HttpTcpClient clientAgent) { mTransferEncoding = false; mRequestLength = 0; Code = 0; mClient = clientAgent; mClient.Client.ClientError = OnSocketError; mClient.Client.DataReceive = OnReveive; mBuffer = mClient.Buffer; Status = RequestStatus.None; mStartTime = TimeWatch.GetElapsedMilliseconds(); mRequestID = System.Threading.Interlocked.Increment(ref mRequestIDSqueue); }
private void SendMessage(AsyncTcpClient client) { ClientToken token = (ClientToken)client.Token; token.RequestTime = TimeWatch.GetElapsedMilliseconds(); token.MessageIndex++; int index = (int)(token.MessageIndex % Messages.Count); var msg = Messages[index]; var data = msg.ToBytes(); client.Send(s => s.Write(data, 0, data.Length)); this.CodeStatistics.Send(data.Length); }
public bool ValidateRPS() { if (MaxRPS == 0) { return(true); } long now = TimeWatch.GetElapsedMilliseconds(); if (now - mLastTime >= 1000) { return(true); } return(mRPS < MaxRPS); }
internal void Increment() { if (MaxRPS > 0) { long now = TimeWatch.GetElapsedMilliseconds(); if (now - mLastTime >= 1000) { mLastTime = now; System.Threading.Interlocked.Exchange(ref mRPS, 1); } else { System.Threading.Interlocked.Increment(ref mRPS); } } }
private void IntervalSend(LinkedList <BeetleX.Clients.AsyncTcpClient> link) { try { Double timestep = (double)Setting.Interval / (double)link.Count; long time = TimeWatch.GetElapsedMilliseconds(); var c = link.Last; int i = 1; while (c != null) { var token = (ClientToken)c.Value.Token; token.LastRequestTime = (long)(time + timestep * i); i++; c = c.Previous; } while (Status == RunStatus.Runing) { var item = link.Last; if (item != null) { var client = item.Value; var token = (ClientToken)client.Token; if (TimeWatch.GetElapsedMilliseconds() - token.LastRequestTime > Setting.Interval) { SendMessage(client); link.RemoveLast(); link.AddFirst(item); token.LastRequestTime = TimeWatch.GetElapsedMilliseconds(); } else { System.Threading.Thread.Sleep(10); } } else { System.Threading.Thread.Sleep(10); } } } catch (Exception e_) { Console.WriteLine(e_.Message + e_.StackTrace); } }
public Task <T> Request <T>(IUniqueMessage <IDType> item, IUniqueMessagePipe <IDType> messagePipe, int timeout = 10000) { AwaitMessage <IDType, T> result = new AwaitMessage <IDType, T>(item._UniqueID); result.TimeOut = TimeWatch.GetElapsedMilliseconds() + timeout; AddMessageAwaiter(result); messagePipe.AwaitBlock = this; try { messagePipe.Write(item); } catch (Exception e_) { ThrowBlockException(item, e_.Message, e_); } return(result.Task); }
private void OnClientReceive(IClient c, ClientReceiveArgs reader) { if (Status == RunStatus.Runing) { AsyncTcpClient client = (AsyncTcpClient)c; ClientToken token = (ClientToken)client.Token; long time = TimeWatch.GetElapsedMilliseconds() - token.RequestTime; this.CodeStatistics.Add(time); PipeStream stream = reader.Stream.ToPipeStream(); int length = (int)stream.Length; this.CodeStatistics.Receive(length); stream.ReadFree(length); if (Setting.Mode == "Response") { SendMessage(client); } } }
public async Task <Response> Execute(Request request) { long runTime = TimeWatch.GetElapsedMilliseconds(); Response response = new Response(); try { response.Status = (short)ResponseCode.SUCCESS; ActionHandler handler = GetActionHandler(request.Url); if (handler == null) { response.Status = (int)ResponseCode.ACTION_NOT_FOUND; response.Data = new object[] { $"{request.Sesion?.RemoteEndPoint} execute {request.Url} not found!" }; } else { var controller = handler.Controller; if (!handler.SingleInstance) { controller = CreateController(handler.ControllerType); } ActionContext context = new ActionContext(this.Server, request, handler, controller); var result = await context.Execute(); if (result != null) { response.Data = new object[] { result } } ; } } catch (Exception e_) { response.Status = (int)ResponseCode.INNER_ERROR; response.Data = new object[] { $"{request.Sesion?.RemoteEndPoint} execute {request.Url} error {e_.Message}" }; if (Server.EnableLog(EventArgs.LogType.Error)) { Server.Log(EventArgs.LogType.Error, $"{request.Sesion?.RemoteEndPoint} execute {request.Url} error {e_.Message}@{e_.StackTrace}"); } } response.ExecuteTime = TimeWatch.GetElapsedMilliseconds() - runTime; return(response); }
private void OnClearLimit(object state) { try { var items = mIpLimitTable.Values.ToArray(); foreach (var item in items) { var now = TimeWatch.GetElapsedMilliseconds(); if (now - item.ActiveTime > 1000 * 600) { mIpLimitTable.TryRemove(item.IP, out LimitItem result); } } } catch (Exception e_) { mHttpServer.GetLog(EventArgs.LogType.Error) ?.Log(EventArgs.LogType.Error, $"IP limit clear error {e_.Message}@{e_.StackTrace}"); } }
internal bool ValidateRPS() { if (MaxRps == 0) { return(true); } long now = TimeWatch.GetElapsedMilliseconds(); if (now - mLastTime >= 1000) { mLastTime = now; System.Threading.Interlocked.Exchange(ref mRPS, 0); return(true); } else { var rps = System.Threading.Interlocked.Increment(ref mRPS); return(rps < MaxRps); } }
public RequestAgent(TcpClientAgent clientAgent, ServerAgent serverAgent, HttpRequest request, HttpResponse response, UrlRouteServerGroup.UrlServerInfo urlServerInfo, Routes.UrlRoute urlRoute) { mTransferEncoding = false; mRequestLength = 0; Code = 0; Server = serverAgent; Request = request; Response = response; mClientAgent = clientAgent; mClientAgent.Client.ClientError = OnSocketError; mClientAgent.Client.DataReceive = OnReveive; mBuffer = mClientAgent.Buffer; Status = RequestStatus.None; UrlServerInfo = urlServerInfo; UrlRoute = urlRoute; mStartTime = TimeWatch.GetElapsedMilliseconds(); mRequestID = System.Threading.Interlocked.Increment(ref mRequestIDSqueue); //System.Threading.Interlocked.Increment(ref RequestCount); //mHistoryRequests[mRequestID] = this; }
private void OnCompleted(EventResponseErrorArgs error) { if (System.Threading.Interlocked.CompareExchange(ref mCompletedStatus, 1, 0) == 0) { Time = TimeWatch.GetElapsedMilliseconds() - mStartTime; mClientAgent.Client.ClientError = null; mClientAgent.Client.DataReceive = null; Server.Push(mClientAgent); //System.Threading.Interlocked.Decrement(ref RequestCount); //mHistoryRequests.Remove(mRequestID, out RequestAgent value); try { if (Request.Server.EnableLog(BeetleX.EventArgs.LogType.Info)) { Request.Server.Log(BeetleX.EventArgs.LogType.Info, $"gateway {Request.RemoteIPAddress} {Request.Method} {Request.Url} request {Server.Host}:{Server.Port} process completed code {Code} time:{Time}"); } UrlRoute.Pluginer.Requested(this); Completed?.Invoke(this); } catch (Exception e_) { if (Request.Server.EnableLog(BeetleX.EventArgs.LogType.Error)) { Request.Server.Log(BeetleX.EventArgs.LogType.Error, $"gateway {Request.RemoteIPAddress} {Request.Method} {Request.Url} request {Server.Host}:{Server.Port} process completed event error {e_.Message}@{e_.StackTrace}"); } } finally { Request.ClearStream(); if (error != null) { Server.Gateway.OnResponseError(error); } else { Request.Recovery(); } } } }
public (int, TaskCompletionSource <Response>) Create(Request request, Type[] resultType, int timeout = 1000 * 100) { int id = 0; long expiredTime; lock (this) { mID++; if (mID >= mEndID) { mID = mStartID; } id = mID; } expiredTime = TimeWatch.GetElapsedMilliseconds() + timeout; var item = new AwaiterItem(); item.ID = id; item.ResultType = resultType; item.Request = request; mAwaiterItemGroup.Set(item.ID, item); return(id, item.Create(expiredTime)); }
private void OnTimeout(object state) { try { mTimer.Change(-1, -1); long timeout = TimeWatch.GetElapsedMilliseconds(); var items = mAwaiterItemGroup.GetTimeouts(timeout); if (items.Count > 0) { for (int i = 0; i < items.Count; i++) { mTimeDispatch.Enqueue(items[i]); } } } catch { } finally { mTimer.Change(1000, 1000); } }
static async Task List(int users) { mCount = 0; List <Task> tasks = new List <Task>(); double start = TimeWatch.GetElapsedMilliseconds(); for (int i = 0; i < users; i++) { var item = Task.Run(async() => { for (int k = 0; k < 10000; k++) { var result = await UserService.List(5); System.Threading.Interlocked.Increment(ref mCount); } }); tasks.Add(item); } Task.WaitAll(tasks.ToArray()); double useTime = TimeWatch.GetElapsedMilliseconds() - start; Console.WriteLine($"[{DateTime.Now:t}][List][Users:{users}|Count:{mCount}|Times:{useTime:######.000}ms|RPS:{(mCount / useTime * 1000):#######}]"); await Task.CompletedTask; }
public bool TimeOut(long time) { return((TimeWatch.GetElapsedMilliseconds() - PingTime) > time); }