示例#1
0
        private async Task SendLoop(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                while (state == State.WaitingForParentConnection)
                {
                    byte[] message = { (byte)CommandCode.ConnectToParent };
                    await udpclient.SendAsync(message, message.Length, parentEndPoint).ConfigureAwait(false);

                    await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
                }

                while (state == State.Working || state == State.Terminating)
                {
                    foreach (var peer in peers)
                    {
                        if (peer.Value.LastPinged.SendAttempts > AttemtsBeforeBan)
                        {
                            await DisconnectPeer(peer.Key).ConfigureAwait(false);

                            continue;
                        }

                        foreach (var message in peer.Value.PendingMessagesLastSendAttempt)
                        {
                            if (message.Value.SendAttempts > AttemtsBeforeBan)
                            {
                                await DisconnectPeer(peer.Key).ConfigureAwait(false);

                                break;
                            }

                            if (DateTime.Now - message.Value.LastSendTime > retryTimeout)
                            {
                                await this.SendMessage(message.Key, peer.Key).ConfigureAwait(false);

                                var newSentData = new MessageSentData(DateTime.Now, message.Value.SendAttempts + 1);
                                peer.Value.PendingMessagesLastSendAttempt[message.Key] = newSentData;
                                peer.Value.LastPinged = newSentData;
                            }
                        }

                        if (DateTime.Now - peer.Value.LastPinged.LastSendTime > retryTimeout)
                        {
                            var    command = (byte)(state == State.Terminating ? CommandCode.Dead : CommandCode.Ping);
                            byte[] message = { command };
                            await udpclient.SendAsync(message, 1, peer.Key).ConfigureAwait(false);

                            var newSentData = new MessageSentData(DateTime.Now, peer.Value.LastPinged.SendAttempts + 1);
                            peer.Value.LastPinged = newSentData;
                        }
                    }

                    await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
                }
            }
        }
示例#2
0
文件: Peer.cs 项目: Glavak/Networking
 public void MarkAlive()
 {
     LastPinged = new MessageSentData(DateTime.Now, 0);
 }