public override void Deliver(Contact source, byte[] message)
        {
            using (MemoryStream mStream = new MemoryStream(message))
            {
                switch ((PacketFlag)mStream.ReadByte())
                {
                    case PacketFlag.PutRequest:
                        {
                            lock (localData)
                            {
                                PutRequest r = Serializer.DeserializeWithLengthPrefix<PutRequest>(mStream, PrefixStyle.Base128);
                                if (r.Data == null)
                                {
                                    byte[] b;
                                    localData.TryRemove(r.Key, out b);
                                }
                                else
                                    localData[r.Key] = r.Data;
                                break;
                            }
                        }
                    case PacketFlag.GetRequest:
                        {
                            GetRequest r = Serializer.DeserializeWithLengthPrefix<GetRequest>(mStream, PrefixStyle.Base128);

                            Callback.SendResponse(RoutingTable.LocalContact, source, r.TokenId, GetData(r.Key));

                            break;
                        }
                    default:
                        break;
                }
            }
        }
        public override void Deliver(Contact source, byte[] message)
        {
            byte flag = message[0];
            Action<Contact, byte[]> processor = processors[flag];

            if (processor != null)
                processor(source, message.Skip(1).ToArray());
        }
 /// <summary>
 /// Sends the response back to the remote end
 /// </summary>
 /// <param name="local">The local contact</param>
 /// <param name="target">The target.</param>
 /// <param name="callbackId">The callback id.</param>
 /// <param name="responseBytes">The response bytes.</param>
 public void SendResponse(Contact local, Contact target, long callbackId, byte[] responseBytes)
 {
     using (MemoryStream m = new MemoryStream())
     {
         Serializer.SerializeWithLengthPrefix<Response>(m, new Response(callbackId, responseBytes), PrefixStyle.Base128);
         target.Send(local, ConsumerId, m.ToArray());
     }
 }
        protected void Send(Contact destination, Guid consumerId, byte flag, byte[] data, bool reliable = true, bool ordered = true, int channel = 1)
        {
            byte[] packet = new byte[data.Length + 1];
            packet[0] = flag;
            Array.ConstrainedCopy(data, 0, packet, 1, data.Length);

            destination.Send(RoutingTable.LocalContact, consumerId, packet, reliable, ordered, channel);
        }
        public ContactCollection(DistributedRoutingTable drt)
        {
            LocalContact = drt.LocalContact;
            NetworkId = drt.NetworkId;
            Configuration = drt.Configuration;
            this.DistributedRoutingTable = drt;

            for (int i = 0; i < buckets.Length; i++)
                buckets[i] = new ContactBucket(drt, i);
        }
        public override TimeSpan Ping(Contact source, TimeSpan timeout)
        {
            if (!IsDead && random.NextDouble() >= PingFailChance)
            {
                Table.DeliverPing(source);

                return TimeSpan.FromMilliseconds(1);
            }
            else
                return TimeSpan.MaxValue;
        }
        /// <summary>
        /// Deliver a message encoded into the given byte array
        /// </summary>
        /// <param name="source">The source of the message</param>
        /// <param name="message">The message.</param>
        public override void Deliver(Contact source, byte[] message)
        {
            using (MemoryStream m = new MemoryStream(message))
            {
                Response r = Serializer.DeserializeWithLengthPrefix<Response>(m, PrefixStyle.Base128);

                WaitToken token;
                if (tokens.TryRemove(r.CallbackId, out token))
                {
                    token.Source = source;
                    token.Response = r.ResponseBytes;
                }
                else if (r.CallbackId > nextId)
                {
                    throw new Exception("Token not found");
                }
            }
        }
        /// <summary>
        /// Deliver a message encoded into the given byte array
        /// </summary>
        /// <param name="source">The source of the message</param>
        /// <param name="message">The message.</param>
        public override void Deliver(Contact source, byte[] message)
        {
            using (MemoryStream m = new MemoryStream(message))
            {
                Response r = Serializer.Deserialize<Response>(m);

                WaitToken token;
                //if (tokens.TryGetValue(r.CallbackId, out token))
                if (tokens.TryRemove(r.CallbackId, out token))
                {
                    token.Response = r.ResponseBytes;
                }
                else
                {
                    throw new Exception("Token not found");
                }
            }
        }
        /// <summary>
        /// Moves the specified contact to the top of the most recently used queue
        /// </summary>
        /// <param name="source">The source.</param>
        internal void Update(Contact source)
        {
#if DEBUG
            if (Configuration.UpdateRoutingTable)
            {
#endif
                if (source == null)
                    return;
                if (source.Identifier == LocalIdentifier)
                    return;
                if (source.NetworkId != NetworkId)
                    throw new ArgumentException("Network Id of contact and ContactCollection must be the same");

                buckets[Identifier512.CommonPrefixLength(source.Identifier, LocalIdentifier)].Update(source);
#if DEBUG
            }
#endif
        }
        public TimeSpan Ping(Contact source, TimeSpan timeout)
        {
            ProxyContact proxySource = (ProxyContact)source;

            MemoryStream m = new MemoryStream();
            Serializer.SerializeWithLengthPrefix<Contact>(m, source, PrefixStyle.Base128);

            m.WriteByte(0);

            var waitToken = Game1.UdpFactory.SendPing(proxySource, this, true);

            Stopwatch timer = new Stopwatch();
            timer.Start();

            if (waitToken.Wait((int)timeout.TotalMilliseconds))
                return timer.Elapsed;

            return TimeSpan.MaxValue;
        }
        public void Send(Contact source, Guid consumerId, byte[] message, bool reliable, bool ordered, int channel)
        {
            MemoryStream m = new MemoryStream();
            Serializer.SerializeWithLengthPrefix<Contact>(m, source, PrefixStyle.Base128);

            m.WriteByte(1);

            m.Write(consumerId.ToByteArray(), 0, 16);

            m.Write(BitConverter.GetBytes(message.Length), 0, 4);
            m.Write(message, 0, message.Length);

            try
            {
                Game1.UdpFactory.Send(m.ToArray(), EndPoint);
            }
            catch (SocketException e)
            {
                Console.WriteLine(e);
            }
        }
 /// <summary>
 /// Deliver a message encoded into the given byte array
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="source">The source of the message</param>
 /// <returns>The response to return</returns>
 public abstract void Deliver(Contact source, byte[] message);
 public override TimeSpan Ping(Contact source, TimeSpan timeout)
 {
     return ProxyInstance.Ping(source, timeout);
 }
        public override TimeSpan Ping(Contact source, TimeSpan timeout)
        {
            UdpContact uSource = source as UdpContact;

            using (MemoryStream m = new MemoryStream())
            {
                using(BinaryWriter w =new BinaryWriter(m))
                {
                    w.Write((byte)PacketFlag.Ping);

                    WriteContact(w, this);

                    var callback = localTable.GetConsumer<Callback>(Callback.CONSUMER_ID);
                    var token = callback.AllocateToken();

                    w.Write(IPAddress.HostToNetworkOrder(token.Id));

                    try
                    {
                        SendUdpMessage(m.ToArray(), Ip, Port);

                        DateTime start = DateTime.Now;
                        if (token.Wait(timeout.Milliseconds))
                        {
                            return DateTime.Now - start;
                        }
                        return TimeSpan.MaxValue;
                    }
                    finally
                    {
                        callback.FreeToken(token);
                    }
                }
            }
        }
        public override void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1)
        {
            base.Send(source, consumerId, message, reliable, ordered, channel);

            using(MemoryStream m = new MemoryStream())
            {
                using(BinaryWriter w = new BinaryWriter(m))
                {
                    w.Write((byte)PacketFlag.Data);

                    WriteContact(w, this);

                    byte[] guidBytes = consumerId.ToByteArray();
                    w.Write(IPAddress.HostToNetworkOrder(guidBytes.Length));
                    w.Write(guidBytes);

                    w.Write(IPAddress.HostToNetworkOrder(message.Length));
                    w.Write(message);

                    SendUdpMessage(m.ToArray(), Ip, Port);
                }
            }
        }
        private bool ConnectToNodeAsParent(Contact node, int timeout)
        {
            bool isAlreadyChild = children.ContainsKey(node);

            bool isAlreadyParent;
            lock (parents)
                isAlreadyParent = parents.Contains(node);

            if (isAlreadyParent || isAlreadyChild)
                return false;

            Callback.WaitToken token = callback.AllocateToken();
            try
            {
                using (MemoryStream m = new MemoryStream())
                {
                    Serializer.SerializeWithLengthPrefix<ParentageRequest>(m, new ParentageRequest()
                    {
                        CallbackId = token.Id,
                    }, PrefixStyle.Base128);

                    base.Send(node, ConsumerId, (byte)PacketFlag.ParentRequest, m.ToArray());
                }

                if (!token.Wait(timeout))
                    return false;

                if (token.Response[0] == 0)
                    return false;

                //add candidate to set of parents, as this request has been successful
                lock (parents)
                {
                    parents.Add(node);
                }

                return true;
            }
            finally
            {
                callback.FreeToken(token);
            }
        }
 /// <summary>
 /// Pings this instance.
 /// </summary>
 /// <returns>The response time, or Timespan.MaxValue if it timed out</returns>
 public abstract TimeSpan Ping(Contact source, TimeSpan timeout);
        private void ParentRequestProcessor(Contact c, byte[] data)
        {
            using (MemoryStream m = new MemoryStream(data))
            {
                var request = Serializer.DeserializeWithLengthPrefix<ParentageRequest>(m, PrefixStyle.Base128);

                if ((ChildrenCount < 2 || children.ContainsKey(c)) && (ParentCount > 0 || Root))
                {
                    callback.SendResponse(RoutingTable.LocalContact, c, request.CallbackId, new byte[] { 1 });

                    children[c] = DateTime.Now;
                }
                else
                {
                    callback.SendResponse(RoutingTable.LocalContact, c, request.CallbackId, new byte[] { 0 });
                }
            }
        }
        private void VideoFrameDataProcessor(Contact c, byte[] data)
        {
            new LoggerMessages.GeneralMessage("Received a frame " + DateTime.Now.Second + " " + DateTime.Now.Millisecond).Send();

            VideoFrame frame = Serializer.DeserializeWithLengthPrefix<VideoFrame>(new MemoryStream(data), PrefixStyle.Base128);

            VideoFrames.Enqueue(frame);

            ThreadPool.QueueUserWorkItem(_ => base.Send(c, ConsumerId, (byte)PacketFlag.Pong, new byte[] { 1 }));

            if (ChildrenCount > 0)
            {
                ThreadPool.QueueUserWorkItem(_ => SendVideoData(data));
                new LoggerMessages.GeneralMessage("Sending a message to a child " + DateTime.Now.Second + " " + DateTime.Now.Millisecond).Send();
            }
        }
 public override void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1)
 {
     ProxyInstance.Send(source, consumerId, message, reliable, ordered, channel);
 }
        public override TimeSpan Ping(Contact source, TimeSpan timeout)
        {
            table.DeliverPing(source);

            return TimeSpan.FromMilliseconds(1);
        }
 /// <summary>
 /// Sends a message to the consumer with the given Id
 /// </summary>
 /// <param name="consumerId">The consumer id.</param>
 /// <param name="message">The message.</param>
 /// <returns>The response fromthe remote consumer, or null if there was no response</returns>
 public virtual void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1)
 {
     Interlocked.Add(ref sentBytes, message.Length);
 }
 public void PingResponse(Contact source, Callback.WaitToken token)
 {
     callback.FreeToken(token);
     table.DeliverPing(source);
 }
 private void PongRequestProcessor(Contact c, byte[] data)
 {
     DateTime d;
     if (children.TryGetValue(c, out d))
         children.TryUpdate(c, DateTime.Now, d);
 }
 /// <summary>
 /// Sends the response back to the remote end
 /// </summary>
 /// <param name="local">The local contact</param>
 /// <param name="target">The target.</param>
 /// <param name="callbackId">The callback id.</param>
 /// <param name="responseBytes">The response bytes.</param>
 public void SendResponse(Contact local, Contact target, long callbackId, byte[] responseBytes)
 {
     using (MemoryStream m = new MemoryStream())
     {
         Serializer.Serialize<Response>(m, new Response(callbackId, responseBytes));
         target.Send(local, ConsumerId, m.ToArray());
     }
 }
 /// <summary>
 /// Sends a message to the consumer with the given Id
 /// </summary>
 /// <param name="consumerId">The consumer id.</param>
 /// <param name="message">The message.</param>
 /// <returns>The response fromthe remote consumer, or null if there was no response</returns>
 public abstract void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1);
 public override void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1)
 {
     table.Deliver(source, consumerId, message);
 }
 public override void Send(Contact source, Guid consumerId, byte[] message, bool reliable = true, bool ordered = true, int channel = 1)
 {
     if (!IsDead && random.NextDouble() >= SendFailChance)
         Table.Deliver(source, consumerId, message);
 }