Ejemplo n.º 1
0
        void listenclient(TcpClient client)
        {
            StringBuilder builder;
            NetworkStream stream = client.GetStream();
            int           i      = 0;

            try
            {
                while (true)
                {
                    builder = new StringBuilder();
                    int    bytes = 0;
                    byte[] data  = new byte[1000000];
                    i = 1;
                    do
                    {
                        bytes = stream.Read(data, 0, data.Length);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (client.Available > 0);
                    string NewPlayer = ExtractLastMessage(data, bytes);
                    Player player    = JsonConvert.DeserializeObject <Player>(NewPlayer);
                    owner.Invoke(new DelPlayer((s) => owner.UpdatePlayer(s)), player);
                }
            }
            catch (Exception ex)
            {
                clients.Remove(client);
                client.Close();
            }
        }
Ejemplo n.º 2
0
        private void CheckHeartBeats()
        {
            if (_isReplica)
            {
                while (true)
                {
                    if (!_heartbeated)
                    {
                        Thread.Sleep(MSEC_PER_ROUND);
                        continue;
                    }
                    TimeSpan diff = (DateTime.Now).Subtract(_lastPrimaryHeartbeat);
                    if (diff.TotalMilliseconds > MSEC_PER_ROUND * 3)  // didnt receive heartbeat in a long time
                    {
                        _primaryDown = true;
                    }

                    if (_primaryDown)
                    {
                        _form.Invoke(new UpdateServerLogDelegate(_form.UpdateServerLogTB), "Primary server is down. Electing new leader");
                        _primaryDown = false;
                        if (ElectLeader())
                        {
                            _isReplica = false;

                            UpdateReplicasPrimary();
                            UpdateClientsServer();

                            _form.Invoke(new UpdateServerLogDelegate(_form.UpdateServerLogTB), $"I'm primary server!");

                            lock (PrimaryServer) {
                                Monitor.Pulse(PrimaryServer);
                            }
                            break;
                        }
                    }
                    Thread.Sleep(MSEC_PER_ROUND);
                }
            }

            if (!_isReplica)  //if primary
            {
                while (true)
                {
                    BroadCastImAlive();
                    Thread.Sleep(MSEC_PER_ROUND / 2);
                }
            }
        }