Ejemplo n.º 1
0
 public void Heartbeat_0不正なID()
 {
     Assert2.ThrowsException <ArgumentException>(() =>
     {
         HeartbeatClient.HeartbeatDataAsync(new NiconicoContext(new NiconicoAuthenticationToken()), "llv1131").GetAwaiter().GetResult();
     });
 }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            var    heartbeatClient = new HeartbeatClient("127.0.0.1", 2020);
            Thread instanceCaller  = new Thread(
                new ThreadStart(heartbeatClient.Run));

            instanceCaller.Start();

            CreateHostBuilder(args).Build().Run();
        }
Ejemplo n.º 3
0
 public void Heartbeat_6エラーデータ_わからない()
 {
     try
     {
         HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/unknown.xml"));
     }
     catch (Exception ex)
     {
         Assert.AreEqual("Parse Error: unknown error, retry later (UNKNOWN)", ex.Message);
     }
 }
Ejemplo n.º 4
0
 public void Heartbeat_5エラーデータ_ログオンしていない()
 {
     try
     {
         HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/not_login.xml"));
     }
     catch (Exception ex)
     {
         Assert.AreEqual("Parse Error: not login (NOTLOGIN)", ex.Message);
     }
 }
Ejemplo n.º 5
0
 public void Heartbeat_4エラーデータ_ストリームが見つからない()
 {
     try
     {
         HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/not_found_stream.xml"));
     }
     catch (Exception ex)
     {
         Assert.AreEqual("Parse Error: stream not found (NOTFOUND_STREAM)", ex.Message);
     }
 }
Ejemplo n.º 6
0
 public void Heartbeat_3エラーデータ_スロットが見つからない()
 {
     try
     {
         HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/not_found_slot.xml"));
     }
     catch (Exception ex)
     {
         Assert.AreEqual("Parse Error: lost slot (NOTFOUND_SLOT)", ex.Message);
     }
 }
Ejemplo n.º 7
0
 public void Heartbeat_2エラーデータ_スロットが存在しない()
 {
     try
     {
         HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/not_exist_slot.xml"));
     }
     catch (Exception ex)
     {
         Assert.AreEqual("Parse Error: slot doesn't exist (NOTEXIST_SLOT)", ex.Message);
     }
 }
Ejemplo n.º 8
0
        public void Heartbeat_1通常データ()
        {
            var ret = HeartbeatClient.ParseHeartbeatData(TestHelper.Load(@"Live/Heartbeat/default.xml"));

            Assert.AreEqual(new DateTimeOffset(2014, 2, 5, 8, 9, 35, TimeSpan.FromHours(9)), ret.LoadedAt);
            Assert.AreEqual(15u, ret.WatchCount);
            Assert.AreEqual(13u, ret.CommentCount);
            Assert.IsFalse(ret.IsRestrict);
            Assert.AreEqual("20929324:lv168235211:0:1391555375:1af6f72ef86eb766", ret.Ticket);
            Assert.AreEqual(TimeSpan.FromSeconds(90), ret.WaitDuration);
        }
Ejemplo n.º 9
0
        async Task ConnectAlways()
        {
            while (true)
            {
                try
                {
                    if (isDisposed)
                    {
                        return;
                    }
                    if (channel.State == ChannelState.Shutdown)
                    {
                        return;
                    }

                    await channel.ConnectAsync();

                    if (isDisposed)
                    {
                        return;
                    }

                    var connectionId = (useSameId) ? this.connectionId : connectionIdFactory();
                    var client       = new HeartbeatClient(channel, connectionId);
                    latestStreamingResult.Dispose();
                    latestStreamingResult = client.Connect();

                    // wait connect complete.
                    await latestStreamingResult.ResponseStream.MoveNext();

                    this.connectionId = connectionId;
                    currentRetryCount = 0;
                    waitConnectComplete.TrySetResult(new object());

                    try
                    {
                        // now channelstate is ready and wait changed.
                        await Task.WhenAny(channel.WaitForStateChangedAsync(ChannelState.Ready), latestStreamingResult.ResponseStream.MoveNext()).ConfigureAwait(false);
                    }
                    finally
                    {
                        waitConnectComplete = new TaskCompletionSource <object>();
                        foreach (var action in disconnectedActions)
                        {
                            action();
                        }
                    }
                }
                catch (Exception ex)
                {
                    GrpcEnvironment.Logger.Error(ex, "Reconnect Failed, Retrying:" + currentRetryCount++);
                }
            }
        }
Ejemplo n.º 10
0
        static void MultiPipeClient()
        {
            string[] pipes = new string[]
            {
                "Client1",
                "Client2",
                "Client3",
                "Client4",
                "Client5",
                "Client6",
                "Client7",
                "Client8"
            };

            Console.WriteLine("Pipe Clients started.");
            senders = new List <IHeartbeatSender>();

            Parallel.For(0, 8, i =>
            {
                HeartBeatGenerator hbgen = new HeartBeatGenerator();
                // dos con clientid
                if ((i == 1) | (i == 3))
                {
                    hbgen.ClientID = string.Format("CName{0}", i);
                }
                // dos con clientid + serial number
                if ((i == 2) | (i == 6))
                {
                    hbgen.ClientID     = string.Format("CIdn{0}", i);
                    hbgen.UsarSerialHB = true;
                }

                IHeartbeatSender sender = new HeartbeatClient(".", pipes[i], 3 * 1000, _enc, 3, hbgen);
                senders.Add(sender);
            });

            Task.Delay(400).Wait();  // esperar que todos los clientes inicien

            foreach (var item in senders)
            {
                item.StartTimer();
            }

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            foreach (var item in senders)
            {
                item.StopTimer();
            }
        }
Ejemplo n.º 11
0
        static private void IniciaClienteShared()
        {
            HeartBeatGenerator hbgen = new HeartBeatGenerator
            {
                ClientID     = "PClient1",
                UsarSerialHB = true
            };

            IHeartbeatSender sender = new HeartbeatClient(server, pipe, 3, _enc, interv, hbgen);

            sender.StartTimer();

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            sender.StopTimer();
        }
Ejemplo n.º 12
0
        static void PipeClient()
        {
            Console.WriteLine("Pipe Client started.");

            HeartBeatGenerator hbgen = new HeartBeatGenerator
            {
                ClientID = "PClient1", UsarSerialHB = true
            };

            IHeartbeatSender sender = new HeartbeatClient(".", "Client1", 3 * 1000, _enc, 3, hbgen);

            sender.StartTimer();

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            sender.StopTimer();
        }
Ejemplo n.º 13
0
        // El método  IniciaClienteShared() implementa el cliente definido en la biblioteca
        // Monitor.Shared.Se presenta como ejemplo de código.
        static private void IniciaClienteShared()
        {
            Console.WriteLine("Udp Client started.");


            HeartBeatGenerator hbgen = new HeartBeatGenerator
            {
                ClientID     = _id,
                UsarSerialHB = false
            };

            IHeartbeatSender sender = new HeartbeatClient(ipad, remPort, locPort, _enc, interv, hbgen);

            sender.StartTimer();

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            sender.StopTimer();
        }
Ejemplo n.º 14
0
        public override async Task StartAsync(CancellationToken stoppingToken)
        {
            try
            {
                // -----------------
                // you'd want to remove this line for production use, once your certs are prod
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
                // -----------------

                var channel = GrpcChannel.ForAddress("http://grpcservice");
                _heartbeatClient = new HeartbeatClient(channel);

                _httpClient = _httpClientFactory.CreateClient("heartbeat");
            }
            catch (Exception x)
            {
                _logger.LogError(x, "Erorr during startup");
            }
            await base.StartAsync(stoppingToken);
        }
Ejemplo n.º 15
0
        static void UdpClient()
        {
            Console.WriteLine("Udp Client started.");


            HeartBeatGenerator hbgen = new HeartBeatGenerator
            {
                ClientID     = "UdpCIdn02",
                UsarSerialHB = false
            };

            IHeartbeatSender sender = new HeartbeatClient("127.0.0.1", 8888, 9090, _enc, 3, hbgen);

            sender.StartTimer();

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            sender.StopTimer();
        }
Ejemplo n.º 16
0
#pragma warning disable CS4014
        public Task StartAsync(CancellationToken cancellationToken)
        {
            // -----------------
            // you'd want to remove this line for production use, once your certs are prod
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            // -----------------

            _channel         = GrpcChannel.ForAddress(Strings.GrpcServiceUrl);
            _heartbeatClient = new HeartbeatClient(_channel);

            Task.Run(async() => {
                await foreach (var response in _heartbeatClient.StreamHeartbeats(new Empty(),
                                                                                 cancellationToken: _cancellationTokenSource.Token).ResponseStream.ReadAllAsync())
                {
                    await _heartbeatHub.Clients.All.SendAsync(Strings.HeartbeatReceivedEventName, response.HostName, response.HostTimeStamp.ToDateTime());
                    _logger.LogInformation($"Streamed heartbeat from {response.HostName}");
                }
            });

            return(Task.CompletedTask);
        }
Ejemplo n.º 17
0
        //  Multiples clientes desde el mismo proceso comparten static HeartBeatGenerator
        // y se sobrescriben las propiedades. SOLO funciona con clientes sin propiedases
        static void MultiUdpClient()
        {
            Console.WriteLine("Udp Clients started.");

            senders = new List <IHeartbeatSender>();

            Parallel.For(0, 9, i =>
            {
                HeartBeatGenerator hbgen = new HeartBeatGenerator();
                // dos con clientid
                if ((i == 1) | (i == 3))
                {
                    hbgen.ClientID = string.Format("CName{0}", i);
                }
                // dos con clientid + serial number
                if ((i == 2) | (i == 6))
                {
                    hbgen.ClientID     = string.Format("CIdn{0}", i);
                    hbgen.UsarSerialHB = true;
                }

                IHeartbeatSender sender = new HeartbeatClient("127.0.0.1", 8888, 9090 + i, _enc, 3, hbgen);
                senders.Add(sender);
            });

            foreach (var item in senders)
            {
                item.StartTimer();
            }

            Console.WriteLine("Press Enter to quit...");
            Console.ReadLine();

            foreach (var item in senders)
            {
                item.StopTimer();
            }
        }
Ejemplo n.º 18
0
        async Task ConnectAlways()
        {
            while (true)
            {
                try
                {
                    if (isDisposed)
                    {
                        return;
                    }
                    if (channel.State == ChannelState.Shutdown)
                    {
                        return;
                    }

                    await channel.ConnectAsync();

                    if (isDisposed)
                    {
                        return;
                    }

                    var connectionId = (useSameId) ? this.connectionId : connectionIdFactory();
                    var client       = new HeartbeatClient(channel, connectionId);
                    latestStreamingResult.Dispose();
                    latestStreamingResult = client.Connect();

                    // wait connect complete.
                    await latestStreamingResult.ResponseStream.MoveNext();

                    this.connectionId = connectionId;
                    currentRetryCount = 0;
                    waitConnectComplete.TrySetResult(new object());

                    bool isFinished = false;
                    try
                    {
                        var heartbeat = Task.Run(async() =>
                        {
                            try
                            {
                                while (true)
                                {
                                    if (isFinished)
                                    {
                                        return;
                                    }
                                    await Task.Delay(TimeSpan.FromSeconds(pingSecond)).ConfigureAwait(false);
                                    if (isFinished)
                                    {
                                        return;
                                    }
                                    await latestStreamingResult.RequestStream.WriteAsync(Nil.Default).ConfigureAwait(false);
                                }
                            }
                            catch { }
                        });

                        await Task.WhenAny(channel.WaitForStateChangedAsync(ChannelState.Ready), latestStreamingResult.ResponseStream.MoveNext(), heartbeat).ConfigureAwait(false);
                    }
                    finally
                    {
                        isFinished = true;

                        waitConnectComplete = new TaskCompletionSource <object>();
                        foreach (var action in disconnectedActions)
                        {
                            action();
                        }
                    }
                }
                catch (Exception ex)
                {
                    GrpcEnvironment.Logger.Error(ex, "Reconnect Failed, Retrying:" + currentRetryCount++);
                }
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Nuclear Watchdog");

            HeartbeatClient client = new HeartbeatClient();
            HeartbeatSender heartbeatSender = new HeartbeatSender(client);

            try {
                heartbeatSender.Register();
            } catch (System.ServiceModel.EndpointNotFoundException)
            {
                Console.WriteLine("Failed to connect to the heartbeat receiver service.");
                Console.WriteLine("Are you sure the service is running?");
                Environment.Exit(1);
            }

            ReactorClient reactor = new ReactorClient();
            ReactorMonitor reactorMonitor = new ReactorMonitor(heartbeatSender, reactor, 350);

            Thread reactorMonitorThread = new Thread(new ThreadStart(reactorMonitor.Monitor));
            reactorMonitorThread.Start();

            Thread heartbeatThread = new Thread(new ThreadStart(heartbeatSender.Beat));
            heartbeatThread.Start();

            // Run for 60 seconds
            Thread.Sleep(60000);

            reactorMonitorThread.Abort();
            reactorMonitorThread.Join();

            heartbeatThread.Abort();
            heartbeatThread.Join();

            heartbeatSender.Unregister();

            Console.WriteLine("Stopping Nuclear Watchdog");
        }
Ejemplo n.º 20
0
        IEnumerator ConnectAlways()
        {
            while (true)
            {
                if (isDisposed)
                {
                    yield break;
                }
                if (channel.State == ChannelState.Shutdown)
                {
                    yield break;
                }

                var conn = channel.ConnectAsync().ToYieldInstruction(false);
                yield return(conn);

                if (isDisposed)
                {
                    yield break;
                }
                if (conn.HasError)
                {
                    GrpcEnvironment.Logger.Error(conn.Error, "Reconnect Failed, Retrying:" + currentRetryCount++);
                    continue;
                }

                var connectionId = (useSameId) ? this.connectionId : connectionIdFactory();
                var client       = new HeartbeatClient(channel, connectionId);
                latestStreamingResult.Dispose();
                var heartBeatConnect = client.Connect().ToYieldInstruction(false);
                yield return(heartBeatConnect);

                if (heartBeatConnect.HasError)
                {
                    GrpcEnvironment.Logger.Error(heartBeatConnect.Error, "Reconnect Failed, Retrying:" + currentRetryCount++);
                    continue;
                }
                else
                {
                    latestStreamingResult = heartBeatConnect.Result;
                }

                var connectCheck = heartBeatConnect.Result.ResponseStream.MoveNext().ToYieldInstruction(false);
                yield return(connectCheck);

                if (connectCheck.HasError)
                {
                    GrpcEnvironment.Logger.Error(heartBeatConnect.Error, "Reconnect Failed, Retrying:" + currentRetryCount++);
                    continue;
                }

                this.connectionId = connectionId;
                currentRetryCount = 0;

                waitConnectComplete.OnNext(Unit.Default);
                waitConnectComplete.OnCompleted();

                var waitForDisconnect = Observable.Amb(channel.WaitForStateChangedAsync(ChannelState.Ready), heartBeatConnect.Result.ResponseStream.MoveNext()).ToYieldInstruction(false);
                yield return(waitForDisconnect);

                try
                {
                    waitConnectComplete = new AsyncSubject <Unit>();
                    foreach (var action in disconnectedActions)
                    {
                        action();
                    }
                }
                catch (Exception ex)
                {
                    GrpcEnvironment.Logger.Error(ex, "Reconnect Failed, Retrying:" + currentRetryCount++);
                }

                if (waitForDisconnect.HasError)
                {
                    GrpcEnvironment.Logger.Error(waitForDisconnect.Error, "Reconnect Failed, Retrying:" + currentRetryCount++);
                }
            }
        }
Ejemplo n.º 21
0
 public HeartbeatSender(HeartbeatClient client)
 {
     this.client = client;
     this.guid = null;
     isActive = false;
 }