Пример #1
0
 public static void StartServerPing()
 {
     if (!string.IsNullOrEmpty(OrderSchemeParameters.СхемаПриказ.УникальныйИдентификаторСтанции))
     {
         timer = EasyTimer.SetInterval(async() =>
         {
             try
             {
                 ВходнойСигнал = await HttpHelper.ПослатьИПолучитьСигнал(new SendSignalDTO
                 {
                     Signal = ShouldSendSignal ? N16Parameters.ВыходнойСигнал : null,
                     Id     = OrderSchemeParameters.СхемаПриказ.УникальныйИдентификаторСтанции
                 });
             }
             catch
             {
                 StopServerPing();
                 ErrorEvent();
             }
         }, 1000);
     }
 }
Пример #2
0
        private void SetPing()
        {
            //var log = LogManager.GetLogger(Global.CallerName());

            if (this.PingIntervalTimer != null)
            {
                PingIntervalTimer.Stop();
            }
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info(string.Format("writing ping packet - expecting pong within {0}ms", PingTimeout));

            PingIntervalTimer = EasyTimer.SetTimeout(() =>
            {
                var log2 = LogManager.GetLogger(Global.CallerName());
                log2.Info("EasyTimer SetPing start");

                Ping();
                OnHeartbeat(PingTimeout);
                log2.Info("EasyTimer SetPing finish");
            }, (int)PingInterval);
        }
Пример #3
0
        internal void OnHeartbeat(long timeout)
        {
            if (this.PingTimeoutTimer != null)
            {
                this.PingTimeoutTimer.Stop();
                this.PingTimeoutTimer = (EasyTimer)null;
            }

            if (timeout <= 0L)
            {
                timeout = this.PingInterval + this.PingTimeout;
            }
            this.PingTimeoutTimer = EasyTimer.SetTimeout((ActionTrigger)(() => {
                LogManager logger = LogManager.GetLogger(Global.CallerName("", 0, ""));
                logger.Info("EasyTimer OnHeartbeat start");
                if (this.ReadyState == Socket.ReadyStateEnum.CLOSED)
                {
                    return;
                }
                this.OnClose("ping timeout", (Exception)null);
                logger.Info("EasyTimer OnHeartbeat finish");
            }), (int)timeout);
        }
Пример #4
0
        public void EasyTimer_ShouldDoWork()
        {
            // Arrange
            var workDone1        = false;
            var watch            = System.Diagnostics.Stopwatch.StartNew();
            var manualResetEvent = new ManualResetEvent(false);

            // Act
            var timer = EasyTimer.SetTimeout(() => {
                workDone1 = true;
                manualResetEvent.Set(); // continue wait
            }, 0);

            watch.Stop();

            manualResetEvent.WaitOne(1000); // pause until set

            // Assert
            if (!workDone1)
            {
                throw new Exception("Task 1 must do work.");
            }
            Assert.InRange(watch.ElapsedMilliseconds, 0, 500); //should be more than enough
        }
        protected override void Write(ImmutableList <Parser.Packet> packets)
        {
            Writable = false;

            try
            {
                foreach (var packet in packets)
                {
                    Parser.Parser.EncodePacket(packet, new WriteEncodeCallback(this));
                }

                // fake drain
                // defer to next tick to allow Socket to clear writeBuffer
                EasyTimer.SetTimeout(() =>
                {
                    Writable = true;
                    Emit(EVENT_DRAIN);
                }, 1);
            }
            catch (Exception e)
            {
                this.OnError("Write", e);
            }
        }
Пример #6
0
        internal void SetPing()
        {
            _pingIntervalTimer?.Stop();

            Logger.Log($"writing ping packet - expecting pong within {PingTimeout}ms");

            _pingIntervalTimer = EasyTimer.SetTimeout(() =>
            {
                Logger.Log("EasyTimer SetPing start");

                if (Upgrading)
                {
                    // skip this ping during upgrade
                    SetPing();
                    Logger.Log("skipping Ping during upgrade");
                }
                else if (ReadyState == ReadyStateEnum.OPEN)
                {
                    Ping();
                    OnHeartbeat(PingTimeout);
                    Logger.Log("EasyTimer SetPing finish");
                }
            }, (int)PingInterval);
        }
Пример #7
0
        private Manager Open(IOpenCallback fn)
        {
            var log = LogManager.GetLogger(Global.CallerName());

            log.Info(string.Format("readyState {0}", ReadyState));
            if (ReadyState == ReadyStateEnum.OPEN)
            {
                return(this);
            }

            log.Info(string.Format("opening {0}", Uri));
            EngineSocket = new Engine(Uri, Opts);
            Quobject.EngineIoClientDotNet.Client.Socket socket = EngineSocket;

            ReadyState = ReadyStateEnum.OPENING;
            OpeningSockets.Add(Socket(Uri.PathAndQuery));
            SkipReconnect = false;

            var openSub = SocketIoClientDotNet.Client.On.Create(socket, Engine.EVENT_OPEN, new ListenerImpl(() =>
            {
                OnOpen();
                if (fn != null)
                {
                    fn.Call(null);
                }
            }));

            var errorSub = Client.On.Create(socket, Engine.EVENT_ERROR, new ListenerImpl((data) =>
            {
                log.Info("connect_error");
                Cleanup();
                ReadyState = ReadyStateEnum.CLOSED;
                EmitAll(EVENT_CONNECT_ERROR, data);

                if (fn != null)
                {
                    var err = new SocketIOException("Connection error", data is Exception ? (Exception)data : null);
                    fn.Call(err);
                }
                MaybeReconnectOnOpen();
            }));

            if (_timeout >= 0)
            {
                var timeout = (int)_timeout;
                log.Info(string.Format("connection attempt will timeout after {0}", timeout));
                var timer = EasyTimer.SetTimeout(() =>
                {
                    var log2 = LogManager.GetLogger(Global.CallerName());
                    log2.Info("Manager Open start");

                    log2.Info(string.Format("connect attempt timed out after {0}", timeout));
                    openSub.Destroy();
                    socket.Close();
                    socket.Emit(Engine.EVENT_ERROR, new SocketIOException("timeout"));
                    EmitAll(EVENT_CONNECT_TIMEOUT, timeout);
                    log2.Info("Manager Open finish");
                }, timeout);

                Subs.Enqueue(new On.ActionHandleImpl(timer.Stop));
                ;
            }

            Subs.Enqueue(openSub);
            Subs.Enqueue(errorSub);
            EngineSocket.Open();

            return(this);
        }
Пример #8
0
            public void Create()
            {
                LogManager log = LogManager.GetLogger(Global.CallerName("", 0, ""));

                try
                {
                    log.Info(string.Format("xhr open {0}: {1}", (object)this.Method, (object)this.Uri));
                    this.Xhr        = (HttpWebRequest)WebRequest.Create(this.Uri);
                    this.Xhr.Method = this.Method;
                    if (this.CookieHeaderValue != null)
                    {
                        this.Xhr.Headers.Add("Cookie", this.CookieHeaderValue);
                    }
                    if (this.ExtraHeaders != null)
                    {
                        foreach (KeyValuePair <string, string> extraHeader in this.ExtraHeaders)
                        {
                            this.Xhr.Headers.Add(extraHeader.Key, extraHeader.Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    this.OnError(ex);
                    return;
                }
                if (this.Method == "POST")
                {
                    this.Xhr.ContentType = "application/octet-stream";
                }
                try
                {
                    if (this.Data != null)
                    {
                        this.Xhr.ContentLength = (long)this.Data.Length;
                        using (Stream requestStream = this.Xhr.GetRequestStream())
                            requestStream.Write(this.Data, 0, this.Data.Length);
                    }
                    EasyTimer.TaskRun((ActionTrigger)(() =>
                    {
                        LogManager logger = LogManager.GetLogger(Global.CallerName("", 0, ""));
                        logger.Info("Task.Run Create start");
                        using (WebResponse response = this.Xhr.GetResponse())
                        {
                            log.Info("Xhr.GetResponse ");
                            Dictionary <string, string> headers = new Dictionary <string, string>();
                            for (int index = 0; index < response.Headers.Count; ++index)
                            {
                                headers.Add(response.Headers.Keys[index], response.Headers[index]);
                            }
                            this.OnResponseHeaders(headers);
                            string header = response.Headers["Content-Type"];
                            using (Stream responseStream = response.GetResponseStream())
                            {
                                Debug.Assert(responseStream != null, "resStream != null");
                                if (header.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase))
                                {
                                    byte[] buffer = new byte[16384];
                                    using (MemoryStream memoryStream = new MemoryStream())
                                    {
                                        int count;
                                        while ((count = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            memoryStream.Write(buffer, 0, count);
                                        }
                                        this.OnData(memoryStream.ToArray());
                                    }
                                }
                                else
                                {
                                    using (StreamReader streamReader = new StreamReader(responseStream))
                                        this.OnData(streamReader.ReadToEnd());
                                }
                            }
                        }
                        logger.Info("Task.Run Create finish");
                    }));
                }
                catch (IOException ex)
                {
                    log.Error("Create call failed", (Exception)ex);
                    this.OnError((Exception)ex);
                }
                catch (WebException ex)
                {
                    log.Error("Create call failed", (Exception)ex);
                    this.OnError((Exception)ex);
                }
                catch (Exception ex)
                {
                    log.Error("Create call failed", ex);
                    this.OnError(ex);
                }
            }
Пример #9
0
            public void Create()
            {
                var log = LogManager.GetLogger(Global.CallerName());

                try
                {
                    log.Info(string.Format("xhr open {0}: {1}", Method, Uri));
                    Xhr             = (HttpWebRequest)WebRequest.Create(Uri);
                    Xhr.Method      = Method;
                    Xhr.Credentials = CredentialCache.DefaultNetworkCredentials;
                    if (CookieHeaderValue != null)
                    {
                        Xhr.Headers.Add("Cookie", CookieHeaderValue);
                        log.Info("added header " + CookieHeaderValue);
                    }
                    else
                    {
                        log.Info("not added header " + CookieHeaderValue);
                    }
                }
                catch (Exception e)
                {
                    log.Error(e);
                    OnError(e);
                    return;
                }


                if (Method == "POST")
                {
                    Xhr.ContentType = "application/octet-stream";
                }

                try
                {
                    if (Data != null)
                    {
                        Xhr.ContentLength = Data.Length;

                        using (var requestStream = Xhr.GetRequestStream())
                        {
                            requestStream.Write(Data, 0, Data.Length);
                        }
                    }

                    EasyTimer.TaskRun(() =>
                    {
                        var log2 = LogManager.GetLogger(Global.CallerName());
                        log2.Info("Task.Run Create start");
                        try
                        {
                            using (var res = Xhr.GetResponse())
                            {
                                log.Info("Xhr.GetResponse ");

                                var responseHeaders = new Dictionary <string, string>();
                                for (int i = 0; i < res.Headers.Count; i++)
                                {
                                    responseHeaders.Add(res.Headers.Keys[i], res.Headers[i]);
                                }
                                OnResponseHeaders(responseHeaders);

                                var contentType = res.Headers["Content-Type"];



                                using (var resStream = res.GetResponseStream())
                                {
                                    Debug.Assert(resStream != null, "resStream != null");
                                    if (contentType.Equals("application/octet-stream",
                                                           StringComparison.OrdinalIgnoreCase))
                                    {
                                        var buffer = new byte[16 * 1024];
                                        using (var ms = new MemoryStream())
                                        {
                                            int read;
                                            while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
                                            {
                                                ms.Write(buffer, 0, read);
                                            }
                                            var a = ms.ToArray();
                                            OnData(a);
                                        }
                                    }
                                    else
                                    {
                                        using (var sr = new StreamReader(resStream))
                                        {
                                            OnData(sr.ReadToEnd());
                                        }
                                    }
                                }
                            }
                            log2.Info("Task.Run Create finish");
                        }
                        catch (System.Net.WebException e)
                        {
                            log2.Error("Task.Run Create failed", e);
                            OnError(e);
                        }
                    });
                }
                catch (System.IO.IOException e)
                {
                    log.Error("Create call failed", e);
                    OnError(e);
                }
                catch (System.Net.WebException e)
                {
                    log.Error("Create call failed", e);
                    OnError(e);
                }
                catch (Exception e)
                {
                    log.Error("Create call failed", e);
                    OnError(e);
                }
            }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.QuestionView);

            // Parse difficulty from Intent.
            string difficulty = Intent.GetStringExtra("Difficulty");

            this.difficultyLevel = DifficultyLevelGet.FromString(difficulty);

            // If timer exists, stop and dispose so a new one can be created.
            if (this.easyTimer != null)
            {
                this.easyTimer.Stop();
                this.easyTimer.Dispose();
                this.easyTimer = null;
            }

            // Assign a countdown/up depending on the difficulty level.
            switch (this.difficultyLevel)
            {
            case DifficultyLevel.Easy:
                // Want to keep track of time they are spending even if not countdown.
                this.easyTimer = new EasyTimer(EasyTimer.TimerType.Up, 1000);
                break;

            case DifficultyLevel.Medium:
                // They have 20 seconds (20000ms) to answer each question.
                this.easyTimer = new EasyTimer(EasyTimer.TimerType.Down, 1000, 20, 0);
                break;

            case DifficultyLevel.Hard:
                // They have 10 seconds (10000ms) to answer each question.
                this.easyTimer = new EasyTimer(EasyTimer.TimerType.Down, 1000, 10, 0);
                break;
            }

            // Load operators.
            if (operators.Count == 0)
            {
                operators.Add(Operator.Add, "+");
                operators.Add(Operator.Subtract, "-");
                operators.Add(Operator.Multiply, "*");
                operators.Add(Operator.Divide, "÷");
            }

            // Load page.
            if (page == null)
            {
                LoadPage();
            }
            else
            {
                // Since the page exists, reset all the values.
                this.score            = 0;
                this.currentQuestion  = null;
                this.totalElapsedTime = 0;
                this.UpdateTextFields();
                this.wrongQuestions.Clear();
            }

            // If they easy, don't show them the time remaining.
            if (this.difficultyLevel == DifficultyLevel.Easy)
            {
                this.txtTimeRemaining.Hide(true);
            }
            else
            {
                this.txtTimeRemaining.Show();

                // Assign countdown logic.
                this.easyTimer.TargetReachedEvent += delegate
                {
                    // If they've answered or the time is already up, ignore when the target reaches, even if it shoudln't.
                    if (this.currentQuestion.Answered && !this.currentQuestion.TimeUp)
                    {
                        return;
                    }

                    // Register the time is up and add register as wrong question.
                    this.currentQuestion.TimeUp = true;
                    this.wrongQuestions.Add(this.currentQuestion);
                };
            }

            // Everytime the timer ticks regardless of difficulty.
            this.easyTimer.Tick(delegate
            {
                // If there is no current question or it is answered, ignore.
                if (this.currentQuestion != null && this.currentQuestion.Answered)
                {
                    return;
                }

                // If their time is up.
                if (this.currentQuestion != null && this.currentQuestion.TimeUp)
                {
                    this.inAnswer.AllowInteraction(false);
                    this.txtTimeRemaining.Color(this.remainingColorNone);
                    this.txtTimeRemaining.Text("TIMEUP!");
                    this.btnSubmit.Text("Next Question");
                }
                else
                {
                    // Track elapsed time as they are still answering the question.
                    // If easy, txtTimeRemaining is hidden so doesn't matter to set text.
                    this.txtTimeRemaining.Text($"{this.easyTimer.Value}s remaining");
                    this.totalElapsedTime++;

                    this.UpdateRemainingColor();
                }
            });

            NextQuestion();
        }
Пример #11
0
        private void Reconnect()
        {
            LogManager log = LogManager.GetLogger(Global.CallerName("", 0, ""));

            if (this.Reconnecting || this.SkipReconnect)
            {
                return;
            }
            ++this.Attempts;
            if (this.Attempts > this._reconnectionAttempts)
            {
                log.Info("reconnect failed");
                this.EmitAll(Manager.EVENT_RECONNECT_FAILED);
                this.Reconnecting = false;
            }
            else
            {
                long num = Math.Min((long)this.Attempts * this.ReconnectionDelay(), this.ReconnectionDelayMax());
                log.Info(string.Format("will wait {0}ms before reconnect attempt", (object)num));
                this.Reconnecting = true;
                this.Subs.Enqueue((ClientOn.IHandle) new ClientOn.ActionHandleImpl(new ActionTrigger(EasyTimer
                                                                                                     .SetTimeout((ActionTrigger)(() => {
                    LogManager logger = LogManager.GetLogger(Global.CallerName("", 0, ""));
                    logger.Info("EasyTimer Reconnect start");
                    logger.Info(string.Format("attempting reconnect"));
                    this.EmitAll(Manager.EVENT_RECONNECT_ATTEMPT, (object)this.Attempts);
                    this.EmitAll(Manager.EVENT_RECONNECTING, (object)this.Attempts);
                    this.Open((Manager.IOpenCallback) new Manager.OpenCallbackImp((Action <object>)(err => {
                        if (err != null)
                        {
                            log.Error("reconnect attempt error", (Exception)err);
                            this.Reconnecting = false;
                            this.Reconnect();
                            this.EmitAll(Manager.EVENT_RECONNECT_ERROR, (object)(Exception)err);
                        }
                        else
                        {
                            log.Info("reconnect success");
                            this.OnReconnect();
                        }
                    })));
                    logger.Info("EasyTimer Reconnect finish");
                }), (int)num).Stop)));
            }
        }
Пример #12
0
        private Manager Open(Manager.IOpenCallback fn)
        {
            LogManager log = LogManager.GetLogger(Global.CallerName("", 0, ""));

            log.Info(string.Format("readyState {0}", (object)this.ReadyState));
            if (this.ReadyState == Manager.ReadyStateEnum.OPEN)
            {
                return(this);
            }
            log.Info(string.Format("opening {0}", (object)this.Uri));
            this.EngineSocket = (Quobject.EngineIoClientDotNet.Client.Socket) new Engine(this.Uri, this.Opts);
            Quobject.EngineIoClientDotNet.Client.Socket socket = this.EngineSocket;
            this.ReadyState = Manager.ReadyStateEnum.OPENING;
            this.OpeningSockets.Add(this.Socket(this.Uri.PathAndQuery));
            this.SkipReconnect = false;
            ClientOn.IHandle openSub = ClientOn.Create((Emitter)socket, EngineIoClientDotNet.Client.Socket.EVENT_OPEN,
                                                       (IListener) new ListenerImpl((ActionTrigger)(() => {
                this.OnOpen();
                if (fn == null)
                {
                    return;
                }
                fn.Call((Exception)null);
            })));
            ClientOn.IHandle handle = ClientOn.Create((Emitter)socket, EngineIoClientDotNet.Client.Socket.EVENT_ERROR,
                                                      (IListener) new ListenerImpl((Action <object>)(data => {
                log.Info("connect_error");
                this.Cleanup();
                this.ReadyState = Manager.ReadyStateEnum.CLOSED;
                this.EmitAll(Manager.EVENT_CONNECT_ERROR, data);
                if (fn != null)
                {
                    fn.Call((Exception) new SocketIOException("Connection error",
                                                              data is Exception ? (Exception)data : (Exception)null));
                }
                else
                {
                    this.MaybeReconnectOnOpen();
                }
            })));
            if (this._timeout >= 0L && this.ReadyState == Manager.ReadyStateEnum.CLOSED)
            {
                int timeout = (int)this._timeout;
                log.Info(string.Format("connection attempt will timeout after {0}", (object)timeout));
                this.Subs.Enqueue((ClientOn.IHandle) new ClientOn.ActionHandleImpl(new ActionTrigger(EasyTimer
                                                                                                     .SetTimeout((ActionTrigger)(() => {
                    LogManager logger = LogManager.GetLogger(Global.CallerName("", 0, ""));
                    logger.Info("Manager Open start");
                    logger.Info(string.Format("connect attempt timed out after {0}", (object)timeout));
                    openSub.Destroy();
                    socket.Close();
                    socket.Emit(Quobject.EngineIoClientDotNet.Client.Socket.EVENT_ERROR,
                                (object)new SocketIOException("timeout"));
                    this.EmitAll(Manager.EVENT_CONNECT_TIMEOUT, (object)timeout);
                    logger.Info("Manager Open finish");
                }), timeout).Stop)));
            }

            this.Subs.Enqueue(openSub);
            this.Subs.Enqueue(handle);
            this.EngineSocket.Open();
            return(this);
        }