Exemplo n.º 1
0
 /// <summary>
 /// 处理新任务
 /// </summary>
 private void ProcessNewTask()
 {
     try
     {
         var newTaskList = this.taskDocker.TaskList.Where(o => o.TaskState == TaskState.NewTask).ToList();
         foreach (var task in newTaskList)
         {
             if (task.TaskState == TaskState.NewTask)
             {
                 LogAgent.Info(String.Format("处理新任务:{0}", task.ToString()));
                 ProcessTask(task);
                 if (task.Dead)
                 {
                     task.Complete();
                 }
                 //else
                 //{
                 //    this.connectionDocker.AddCase(task.GetRelatedProtocol());
                 //}
             }
         }
     }
     catch (Exception exception)
     {
         var m = exception.Message;
         LogAgent.Error("处理新任务:" + m.ToString());
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// 执行方法前先执行这
 /// </summary>
 /// <param name="context"></param>
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     base.OnActionExecuting(context);
     try
     {
         string        Moudle         = String.Format("接收[{0}-{1}]请求 {2}", MoudleName, MethodName, context.ActionDescriptor.DisplayName);
         string        RequestAddress = String.Format("RequestAddress:       {0}:{1}", context.HttpContext.Connection.RemoteIpAddress.ToString(), context.HttpContext.Connection.RemotePort.ToString());
         string        URL            = String.Format("uri:                  {0}", context.HttpContext.Request.Path.Value.ToString());
         string        method         = String.Format("method:               {0}", context.HttpContext.Request.Method.ToString());
         string        contentType    = String.Format("contentType:          {0}", context.HttpContext.Request.ContentType == null ? "null" : context.HttpContext.Request.ContentType.ToString());
         string        parameter      = String.Format("parameter:            {0}", JsonConvert.SerializeObject(context.ActionArguments));
         StringBuilder message        = new StringBuilder();
         message.AppendLine(Moudle);
         message.AppendLine(RequestAddress);
         message.AppendLine(URL);
         message.AppendLine(method);
         message.AppendLine(contentType);
         message.AppendLine(parameter);
         LogAgent.Info(message.ToString());
         CounterToken counterToken = LogAgent.StartCounter();
         context.ActionDescriptor.Properties.TryAdd("Action-" + context.HttpContext.TraceIdentifier, counterToken);
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
 }
Exemplo n.º 3
0
        private void Execute()
        {
            if (cts.Token.IsCancellationRequested)
            {
                return;
            }
            var list = this.GetExecutors();

            foreach (var item in list)
            {
                Task.Factory.StartNew(() => {
                    item.Run();
                });
            }
            var dt = DateTime.Now;

            dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
            var next = dt.AddMinutes(1);
            var due  = Convert.ToInt32(Math.Ceiling((next - DateTime.Now).TotalMilliseconds));

            Task.Factory.StartNew(async() => {
                try
                {
                    await Task.Delay(due, cts.Token);
                    Execute();
                }
                catch (Exception ex)
                {
                    LogAgent.Error(ex.ToString());
                }
            }, cts.Token);
        }
Exemplo n.º 4
0
        public void Close()
        {
            if (_client == null)
            {
                return;
            }

            var oldValue = Interlocked.Exchange(ref _client, null);

            if (oldValue == null)
            {
                return;
            }

            var cacheResult = SimpleRpcClientPoolRoot.ReturnItem(oldValue);

            if (cacheResult == false)
            {
                try
                {
                    oldValue.Dispose();
                }
                catch
                {
                    LogAgent.Error("SimpleRpcCLient Dispose error");
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="index"></param>
        /// <param name="length"></param>
        /// <param name="destination"></param>
        public override void Send(byte[] buffer, int index, int length, INode destination)
        {
            var clientSocket = SocketMap[destination.nodeConfig.ToString()];

            try
            {
                if (clientSocket.WasDisposed)
                {
                    CloseConnection(clientSocket);
                    return;
                }
                var buf = Allocator.Buffer(length);
                buf.WriteBytes(buffer, index, length);
                Encoder.Encode(ConnectionAdapter, buf, out List <IByteBuf> encodedMessages);
                foreach (var message in encodedMessages)
                {
                    var state = CreateNetworkState(clientSocket.Local, destination, message, 0);
                    ListenerSocket.BeginSendTo(message.ToArray(), 0, message.ReadableBytes, SocketFlags.None,
                                               destination.ToEndPoint <EndPoint>(), SendCallback, state);
                    LogAgent.Info(String.Format("发送数据-{0}-->>{1}", this.Listener.reactorType, this.Encoder.ByteEncode(message.ToArray())));
                    clientSocket.Receiving = true;
                }
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
                CloseConnection(ex, clientSocket);
            }
        }
Exemplo n.º 6
0
        public void OnException(ExceptionContext context)
        {
            JsonResponses jsonResponses = JsonResponses.Failed.Clone();
            Exception     ex            = context.Exception;
            string        errMsg        = "Exception:" + ex.ToString();

            if (context.Exception.GetType() == typeof(ErrorCodeException))
            {
                ErrorCodeException errorCodeException = (ErrorCodeException)ex;
                //针对不同的自定义异常,做不同处理
                jsonResponses.code = errorCodeException.GetErrorCode();
                jsonResponses.msg  = errorCodeException.GetErrorMsg();
            }
            else if (context.Exception.GetType() == typeof(WebSocketException))
            {
                //针对不同的自定义异常,做不同处理
                WebSocketException errorCodeException = (WebSocketException)ex;
                jsonResponses.code = errorCodeException.ErrorCode;
                jsonResponses.msg  = errorCodeException.Message;
            }
            else if (context.Exception.GetType() == typeof(ArgumentException))
            {
                //针对不同的自定义异常,做不同处理
                ArgumentException errorCodeException = (ArgumentException)ex;
                jsonResponses.msg = errorCodeException.Message;
            }
            else
            {
                jsonResponses.msg = "系统错误";
            }
            context.Result           = new JsonResult(jsonResponses);
            context.ExceptionHandled = true;
            LogAgent.Error(errMsg + " " + JsonConvert.SerializeObject(jsonResponses));
        }
Exemplo n.º 7
0
 /// <summary>
 /// 接收数据回调[协议进程]
 /// </summary>
 /// <param name="receiveState"></param>
 protected void ReceiveCallback(NetworkState receiveState)
 {
     try
     {
         if (receiveState.RemoteHost == null)
         {
             return;
         }
         var received = receiveState.RawBuffer.Length;
         if (received == 0)
         {
             return;
         }
         receiveState.Buffer.WriteBytes(receiveState.RawBuffer, 0, received);
         List <IByteBuf> decoded;
         Decoder.Decode(ConnectionAdapter, receiveState.Buffer, out decoded);
         foreach (var message in decoded)
         {
             var networkData = NetworkData.Create(receiveState.RemoteHost, message);
             LogTemplate("处理数据-{0}-->>{1}", networkData.Buffer);
             if (ConnectionAdapter is ReactorConnectionAdapter)
             {//合法消息回调到线程进行分发处理
                 ((ReactorConnectionAdapter)ConnectionAdapter).networkDataDocker.AddNetworkData(networkData);
                 ((EventWaitHandle)((ReactorConnectionAdapter)ConnectionAdapter).protocolEvents[(int)ProtocolEvents.PortReceivedData]).Set();
             }
         }
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// 判断异步任务是否超时并处理。
 /// </summary>
 private void ProcessAsyncTaskOvertime()
 {
     try
     {
         lock (this.taskDocker.TaskList)
         {
             var taskList = this.taskDocker.TaskList;
             for (int i = 0; i < taskList.Count; ++i)
             {
                 if (taskList[i].AsyncTaskOvertime || taskList[i].Dead)
                 {
                     RemoveTask(taskList[i]);
                     continue;
                 }
                 //检查任务对应的协议是否超时
                 if (taskList[i].GetRelatedProtocol().Dead)
                 {
                     taskList[i].Complete(TaskState.TaskOvertime);
                 }
                 else
                 {
                     this.taskDocker.SetTaskTimeout(taskList[i].GetRelatedProtocol());
                 }
             }
         }
     }
     catch (Exception ex)
     {
         string msg = string.Format("ProcessAsyncTaskOvertime:{0}", ex.ToString());
         LogAgent.Error(msg);
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// 网卡ID
 /// </summary>
 /// <returns></returns>
 private static string MacId()
 {
     try
     {
         return(Identifier("Win32_NetworkAdapterConfiguration",
                           "MACAddress", "IPEnabled"));
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return("");
 }
Exemplo n.º 10
0
 /// <summary>
 /// 显卡
 /// </summary>
 /// <returns></returns>
 private static string VideoId()
 {
     try
     {
         return(Identifier("Win32_VideoController", "DriverVersion")
                + Identifier("Win32_VideoController", "Name"));
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return("");
 }
Exemplo n.º 11
0
 /// <summary>
 /// 设置键
 /// </summary>
 /// <param name="KeyValue"></param>
 /// <param name="Path"></param>
 /// <param name="KeyField"></param>
 public static void SetSecurityLey(string KeyValue, string Path, string KeyField)
 {
     try
     {
         using (var tempk = Registry.CurrentUser.CreateSubKey(Path))
         {
             tempk.SetValue(KeyField, KeyValue);
         }
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
 }
Exemplo n.º 12
0
        private void RunExecute()
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            Interlocked.Increment(ref flag);
            var serviceScope = services.CreateScope();

            try
            {
                var argtypes = type.GetConstructors()
                               .First()
                               .GetParameters()
                               .Select(x => serviceScope.ServiceProvider.GetService(x.ParameterType))
                               .ToArray();
                var instance = Activator.CreateInstance(type.AsType(), argtypes);


                var infos      = method.GetParameters();
                var paramtypes = new object[infos.Length];
                for (int i = 0; i < infos.Length; i++)
                {
                    var info = infos[i];
                    if (info.ParameterType == typeof(CancellationToken))
                    {
                        paramtypes[i] = cancellationToken;
                    }
                    else
                    {
                        paramtypes[i] = serviceScope.ServiceProvider.GetService(info.ParameterType);
                    }
                }
                var result = method.Invoke(instance, paramtypes);
                if (result is Task task)
                {
                    task.Wait();
                }
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
            }
            finally
            {
                serviceScope.Dispose();
                Interlocked.Decrement(ref flag);
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// 设置缓存
 /// </summary>
 /// <param name="PlatformNo"></param>
 /// <param name="platforms"></param>
 /// <returns></returns>
 public bool SetPlatformList(long PlatformNo, List <OptionValue> platforms)
 {
     try
     {
         string key   = String.Format("{0}_{1}", RedisKey.PlatformKeyPre, PlatformNo.ToString());
         string value = platforms.SerializeToString();
         RedisHandleManager.Instance().RedisStringHandle.Set(key, value);
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
         return(false);
     }
     return(true);
 }
Exemplo n.º 14
0
 /// <summary>
 /// 主物理硬盘驱动器ID
 /// </summary>
 /// <returns></returns>
 private static string DiskId()
 {
     try
     {
         return(Identifier("Win32_DiskDrive", "Model")
                + Identifier("Win32_DiskDrive", "Manufacturer")
                + Identifier("Win32_DiskDrive", "Signature")
                + Identifier("Win32_DiskDrive", "TotalHeads"));
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return("");
 }
Exemplo n.º 15
0
 /// <summary>
 /// 主板
 /// </summary>
 /// <returns></returns>
 private static string BaseId()
 {
     try
     {
         return
             //Identifier("Win32_BaseBoard", "Model") +
             (Identifier("Win32_BaseBoard", "Manufacturer")
              + Identifier("Win32_BaseBoard", "Name")
              + Identifier("Win32_BaseBoard", "SerialNumber"));
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return("");
 }
Exemplo n.º 16
0
 /// <summary>
 /// 返回BIOS标识符
 /// </summary>
 /// <returns></returns>
 private static string BiosId()
 {
     try
     {
         return(Identifier("Win32_BIOS", "Manufacturer")
                + Identifier("Win32_BIOS", "SMBIOSBIOSVersion")
                //+ Identifier("Win32_BIOS", "IdentificationCode")
                + Identifier("Win32_BIOS", "SerialNumber")
                + Identifier("Win32_BIOS", "ReleaseDate")
                + Identifier("Win32_BIOS", "Version"));
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return("");
 }
Exemplo n.º 17
0
        public JsonResponse Validate(string token, string OriginalStr)
        {
            JsonResponse jsonResponse = JsonResponse.Failed.Clone() as JsonResponse;

            try
            {
                string json = Decrypt(token);
                if (!String.IsNullOrEmpty(json))
                {
                    Dictionary <string, object> Payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
                    if (Payload.ContainsKey("jti") && OriginalStr == Payload["jti"].ToString())
                    {
                        jsonResponse.code = JsonResponse.SuccessCode;
                        jsonResponse.data = Payload;
                        jsonResponse.msg  = "激活成功";
                    }
                    else
                    {
                        jsonResponse.code = (int)ErrorCodeEnums.MacCodeKeyChange;
                        jsonResponse.msg  = ErrorCodeEnums.MacCodeKeyChange.GetEnumDescription();
                        LogAgent.Info(String.Format("tokenKey:{0};LocalKey:{1}", OriginalStr, Payload["jti"].ToString()));
                    }
                    return(jsonResponse);
                }
                jsonResponse.msg  = ErrorCodeEnums.SignatureKeyEmpty.GetEnumDescription();
                jsonResponse.code = (int)ErrorCodeEnums.SignatureKeyEmpty;
            }
            catch (TokenExpiredException ex)
            {
                jsonResponse.msg  = ErrorCodeEnums.TokenExpired.GetEnumDescription();
                jsonResponse.code = (int)ErrorCodeEnums.TokenExpired;
                LogAgent.Info(String.Format("token:{0};ExpiredTime:{1}", token, ex.Expiration));
            }
            catch (SignatureVerificationException)
            {
                jsonResponse.msg  = ErrorCodeEnums.SignatureError.GetEnumDescription();
                jsonResponse.code = (int)ErrorCodeEnums.SignatureError;
            }
            catch (Exception ex)
            {
                jsonResponse.msg = "该激活码不正确!";
                LogAgent.Error(ex.ToString());
            }
            LogAgent.Info("Validate:" + token + ";result:" + jsonResponse.msg);
            return(jsonResponse);
        }
Exemplo n.º 18
0
        public static string HttpGet(BrowserPara browserPara)
        {
            try
            {
                LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
                HttpWebRequest request = WebRequest.Create(browserPara.Uri) as HttpWebRequest;
                //每次请求绕过代理,解决第一次调用慢的问题
                request.Proxy = null;
                //使用已经保存的cookies
                //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
                ServicePoint currentServicePoint = request.ServicePoint;
                currentServicePoint.ConnectionLimit = 1000;
                if (browserPara.Headers != null)
                {
                    foreach (var header in browserPara.Headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
                string cookie = GetCookie();
                if (!String.IsNullOrEmpty(cookie))
                {
                    request.Headers.Add("Cookie", cookie);
                }

                string str;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                        str = reader.ReadToEnd();
                    }
                    ProcessResponseCookies(request, response);
                    request.Abort();
                    request = null;
                }
                LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, str);
                return(str);
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
            }
            return(String.Empty);
        }
Exemplo n.º 19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="PlatformNo"></param>
 /// <param name=""></param>
 /// <returns></returns>
 public List <OptionValue> GetPlatformList(long PlatformNo)
 {
     try
     {
         string key   = String.Format("{0}_{1}", RedisKey.PlatformKeyPre, PlatformNo.ToString());
         string value = RedisHandleManager.Instance().RedisStringHandle.Get(key);
         if (String.IsNullOrEmpty(value))
         {
             return(null);
         }
         value = JsonArrayObjects.Parse(value).ToJson();
         return(value.FromJson <List <OptionValue> >());
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return(null);
 }
Exemplo n.º 20
0
 /// <summary>
 /// 执行方法后执行这
 /// </summary>
 /// <param name="context"></param>
 public override void OnActionExecuted(ActionExecutedContext context)
 {
     base.OnActionExecuted(context);
     try
     {
         object obj    = null;
         bool   result = context.ActionDescriptor.Properties.TryGetValue("Action-" + context.HttpContext.TraceIdentifier, out obj);
         if (result && obj is CounterToken)
         {
             CounterToken counterToken = (CounterToken)obj;
             LogAgent.StopCounterAndLog(counterToken, String.Format("结束[{0}-{1}]请求{2}", MoudleName, MethodName, context.ActionDescriptor.DisplayName));
             return;
         }
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="KeyField"></param>
        /// <returns></returns>
        public static string GetRegeditkeyValue(string Path, string KeyField)
        {
            string ret = string.Empty;

            try
            {
                using (var obj = Registry.CurrentUser.OpenSubKey(Path, true))
                {
                    if (obj != null)
                    {
                        var value = obj.GetValue(KeyField);
                        if (value != null)
                        {
                            ret = Convert.ToString(value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
            }
            return(ret);
        }
Exemplo n.º 22
0
        ///// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="receiveState"></param>
        private void PortDataReceived(IAsyncResult ar)
        {
            var receiveState = (NetworkState)ar.AsyncState;

            try
            {
                var received = ListenerSocket.EndReceiveFrom(ar, ref RemoteEndPoint);
                if (received == 0)
                {
                    return;
                }
                NetworkData networkData = NetworkData.Create(this.Listener, receiveState.RawBuffer, received);
                networkData.RemoteHost.EndNodePoint = RemoteEndPoint;
                this.ReceivedData(networkData);
                //清除数据继续接收
                receiveState.RawBuffer = new byte[this.BufferSize];
                ListenerSocket.BeginReceiveFrom(this.networkState.RawBuffer, 0, this.networkState.RawBuffer.Length, SocketFlags.None,
                                                ref RemoteEndPoint, PortDataReceived, this.networkState);
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.ToString());
            }
        }
Exemplo n.º 23
0
        private void AcceptSocketCallback(IAsyncResult ar)
        {
            if (_serverState != 1)
            {
                return;
            }

            var server = (Socket)ar.AsyncState;

            Socket     client     = null;
            IPEndPoint ipEndPoint = null;

            try
            {
                client     = server.EndAccept(ar);
                ipEndPoint = (IPEndPoint)client.RemoteEndPoint;
            }
            catch (Exception ex)
            {
                LogAgent.Error(ex.Message);
            }

            try
            {
                server.BeginAccept(AcceptSocketCallback, server);
            }
            catch (Exception ex)
            {
                Close();
                try
                {
                    if (client != null)
                    {
                        client.Close();
                    }
                }
                catch
                {
                }

                LogAgent.Error(ex.Message);

                return;
            }

            if (ipEndPoint == null)
            {
                try
                {
                    if (client != null)
                    {
                        client.Close();
                    }
                }
                catch
                {
                }

                return;
            }

            var tcpTransport = new TcpTransport(this, ipEndPoint.Address, ipEndPoint.Port);

            try
            {
                tcpTransport.Init(client);
            }
            catch (Exception ex)
            {
                try
                {
                    tcpTransport.Close();
                }
                catch
                {
                }

                LogAgent.Error(ex.Message);
                return;
            }

            _clientTransportDictionary[tcpTransport.Key] = tcpTransport;
        }
Exemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public ServerBootstrap(IServiceProvider services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var options = new ServerOptions();
            var types   = GetTypeInfos(options as ServerOptions);
            var list    = new List <JobExecutor>();

            foreach (var type in types)
            {
                foreach (var method in type.DeclaredMethods)
                {
                    var attribute = method.GetCustomAttribute <ScheduleAttribute>();
                    if (attribute != null)
                    {
                        if (string.IsNullOrEmpty(attribute.Name))
                        {
                            throw new CustomAttributeFormatException("Crontab name is empty");
                        }
                        var arr = attribute.Schedule.Split('|');
                        if (arr.Length == 0)
                        {
                            throw new CustomAttributeFormatException($"Crontab '{attribute.Name}' does not have any schedule");
                        }
                        var schedules = new JobSchedule[arr.Length];
                        for (int i = 0; i < arr.Length; i++)
                        {
                            if (JobSchedule.TryParse(arr[i], out JobSchedule schedule))
                            {
                                schedules[i] = schedule;
                            }
                            else
                            {
                                throw new CustomAttributeFormatException($"Crontab '{attribute.Name}' schedule '{arr[i]}' format error");
                            }
                        }
                        var name = attribute.Name;
                        if (string.IsNullOrEmpty(name))
                        {
                            name = method.Name;
                        }
                        var item = new JobExecutor(name, services, cts.Token, type, method, schedules, attribute.AllowConcurrentExecution, attribute.RunImmediately);
                        if (!executorDict.ContainsKey(item.Name))
                        {
                            executorDict.Add(item.Name, item);
                            if (attribute.AutoEnable)
                            {
                                item.Enable();
                            }
                        }
                        else
                        {
                            throw new CustomAttributeFormatException($"Crontab '{item.Name}' name is duplicate");
                        }
                    }
                }
            }

            var dt = DateTime.Now;

            dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
            var next = dt.AddMinutes(1);
            var due  = Convert.ToInt32(Math.Ceiling((next - DateTime.Now).TotalMilliseconds));

            Task.Factory.StartNew(async() => {
                try
                {
                    await Task.Delay(due, cts.Token);
                    Execute();
                }
                catch (Exception ex)
                {
                    LogAgent.Error(ex.ToString());
                }
            }, cts.Token);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 开始任务
        /// </summary>
        public void Start()
        {
            WorkerTask = Task.Factory.StartNew(async delegate {
                while (!CancelTokenSource.IsCancellationRequested && !this.IsCompleted)
                {
                    try
                    {
                        //发送任务列表
                        var toSend = new List <Task>();
                        foreach (var n in this.TakeMany())
                        {
                            var t = Connection.Send(n);
                            // Keep the continuation
                            var cont = t.ContinueWith(ct => {
                                var cn = n;
                                var ex = t.Exception;
                                if (ex == null)
                                {
                                    Broker.RaiseNotificationSucceeded(cn);
                                }
                                else
                                {
                                    Broker.RaiseNotificationFailed(cn, ex);
                                }
                            });
                            // Let's wait for the continuation not the task itself
                            toSend.Add(cont);
                        }

                        if (toSend.Count <= 0)
                        {
                            continue;
                        }
                        try
                        {
                            LogAgent.Info("Waiting on all tasks {0}", toSend.Count());
                            await Task.WhenAll(toSend).ConfigureAwait(false);
                            LogAgent.Info("All Tasks Finished");
                        }
                        catch (Exception ex)
                        {
                            LogAgent.Error("Waiting on all tasks Failed: {0}", ex);
                        }
                        LogAgent.Info("Passed WhenAll");
                    }
                    catch (Exception ex)
                    {
                        LogAgent.Error("Broker.Take: {0}", ex);
                    }
                }

                if (CancelTokenSource.IsCancellationRequested)
                {
                    LogAgent.Info("Cancellation was requested");
                }
                if (this.IsCompleted)
                {
                    LogAgent.Info("Broker IsCompleted");
                }
                LogAgent.Debug("Broker Task Ended");
            }, CancelTokenSource.Token, TaskCreationOptions.LongRunning
                                               | TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();

            //工作任务异常的延续任务
            WorkerTask.ContinueWith(t => {
                var ex = t.Exception;
                if (ex != null)
                {
                    LogAgent.Error("ServiceWorkerAdapter.WorkerTask Error: {0}", ex);
                }
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
Exemplo n.º 26
0
 /// <summary>
 /// 启动WebSocket
 /// </summary>
 protected override void PushServerStart()
 {
     try
     {
         if (SocketParam == null)
         {
             return;
         }
         this.Websocket = new WebSocketServer();
         bool IsSetup = false;
         if (SocketParam.IsUseCertificate)
         {
             IsSetup = this.Websocket.Setup(new RootConfig(),
                                            new ServerConfig
             {
                 Name = SocketParam.ServerName,
                 MaxConnectionNumber = 1000,
                 Mode                     = SocketMode.Tcp,
                 Port                     = SocketParam.Port, //80,
                 ClearIdleSession         = false,
                 ClearIdleSessionInterval = 86400,
                 ListenBacklog            = 1000,
                 ReceiveBufferSize        = 1024,
                 SendBufferSize           = 1024,
                 KeepAliveInterval        = 1,
                 KeepAliveTime            = 55,
                 Security                 = SocketParam.ServerSecurity,
                 SyncSend                 = false,
                 Certificate              = new CertificateConfig
                 {
                     StoreName     = SocketParam.ServerStoreName,
                     StoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
                     Thumbprint    = SocketParam.ServerThumbprint
                 }
             }, new SuperSocket.SocketEngine.SocketServerFactory());
         }
         else
         {
             IsSetup = Websocket.Setup(new RootConfig(), new ServerConfig
             {
                 Name = SocketParam.ServerName,
                 MaxConnectionNumber = 1000,
                 Port                     = SocketParam.Port,
                 SyncSend                 = false,
                 ClearIdleSession         = false,
                 ClearIdleSessionInterval = 86400,
             });
         }
         if (IsSetup == false)
         {
             LogAgent.Info(Websocket.Name + " Failed to setup!");
             return;
         }
         LogAgent.Info(Websocket.Name + " Setup Success...!");
         this.Websocket.NewSessionConnected += WebSocket_NewSessionConnected;
         this.Websocket.NewMessageReceived  += WebSocket_NewMessageReceived;
         this.Websocket.SessionClosed       += WebSocket_SessionClosed;
         if (this.Websocket.Start() == false)
         {
             LogAgent.Info(Websocket.Name + " Failed to start!");
             return;
         }
         LogAgent.Info("Server Listen at " + this.Websocket.Listeners[0].EndPoint.Address.ToString());
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
 }
Exemplo n.º 27
0
 public static string HttpPost(BrowserPara browserPara)
 {
     try
     {
         LogAgent.Info("[Request]->Url:{0};Parameter:{1};Method:{2}", browserPara.Uri, browserPara.PostData, browserPara.Method.ToString());
         HttpWebRequest request = WebRequest.Create(browserPara.Uri) as HttpWebRequest;
         //将发送数据转换为二进制格式
         byte[] byteArray = Encoding.UTF8.GetBytes(browserPara.PostData);
         //要POST的数据大于1024字节的时候, 浏览器并不会直接就发起POST请求, 而是会分为俩步:
         //1. 发送一个请求, 包含一个Expect:100-continue, 询问Server使用愿意接受数据
         //2. 接收到Server返回的100-continue应答以后, 才把数据POST给Server
         //直接关闭第一步验证
         request.ServicePoint.Expect100Continue = false;
         //是否使用Nagle:不使用,提高效率
         request.ServicePoint.UseNagleAlgorithm = false;
         //设置最大连接数
         request.ServicePoint.ConnectionLimit = 65500;
         //指定压缩方法
         //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
         //使用已经保存的cookies
         request.KeepAlive     = false;
         request.ContentType   = browserPara.ContentType;
         request.Method        = HttpMethod.Post.Method.ToString();
         request.Timeout       = browserPara.Timeout;
         request.ContentLength = byteArray.Length;
         //关闭缓存
         request.AllowWriteStreamBuffering = false;
         //每次请求绕过代理,解决第一次调用慢的问题
         request.Proxy = null;
         //多线程并发调用时默认2个http连接数限制的问题,讲其设为1000
         ServicePoint currentServicePoint = request.ServicePoint;
         if (browserPara.Headers != null)
         {
             foreach (var header in browserPara.Headers)
             {
                 request.Headers.Add(header.Key, header.Value);
             }
         }
         string cookie = GetCookie();
         if (!String.IsNullOrEmpty(cookie))
         {
             request.Headers.Add("Cookie", cookie);
         }
         string responseFromServer = String.Empty;
         using (Stream dataStream = request.GetRequestStream())
         {
             dataStream.Write(byteArray, 0, byteArray.Length);
             using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
             {
                 //获取服务器返回的数据流
                 using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                 {
                     responseFromServer = reader.ReadToEnd();
                 }
                 ProcessResponseCookies(request, response);
             }
             request.Abort();
         }
         LogAgent.Info("[Response]->Url:{0};{1}", browserPara.Uri, responseFromServer);
         return(responseFromServer);
     }
     catch (Exception ex)
     {
         LogAgent.Error(ex.ToString());
     }
     return(String.Empty);
 }