Exemple #1
0
        /// <summary>
        /// Send a new FPR to the peer for download the next not-downloaded file pack of a this file part.
        /// </summary>
        /// <param name="download">The download object.</param>
        /// <param name="Peer">The IP address of peer to send the FPR message.</param>
        /// <returns>Return true if the message has been sended.</returns>
        private static bool DownloadFirstNotDownloadedFilePack(Objects.Download download, Objects.Peer Peer)
        {
            for (int i = 0; i < download.ListFileParts.Length; i++)
            {
                if (download.ListFileParts[i] > 0)
                {
                    int a = i * 128;

                    for (int n = 0; n < 128; n++)
                    {
                        if (download.ListFilePacks[a + n] == false)
                        {
                            // start to download the file part

                            string[] Params = new string[3];
                            Params[0] = download.Name;
                            Params[1] = download.SHA1;
                            Params[2] = ((a + n) * 16384).ToString();

                            Messages.IMessage FprMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.FPR, Params);

                            Peer.Send(FprMess);

                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemple #2
0
        /// <summary>
        /// Send a new FPR to the peer for download a file pack of a not-downloading file part.
        /// </summary>
        /// <param name="download">The download object.</param>
        /// <param name="Peer">The IP address of peer to send the FPR message.</param>
        /// <returns>Return true if the message has been sended.</returns>
        private static bool StartDownloadNextFilePart(Objects.Download download, Objects.Peer Peer)
        {
            // the index of the not-downloaded file parts
            int[] index = new int[download.RemainingFileParts];

            int n = 0;

            // get the not-downloaded file parts
            for (int i = 0; i < download.ListFileParts.Length; i++)
            {
                if (download.ListFileParts[i] == 128 || (download.ListFileParts[i] > 0 && i == (download.ListFileParts.Length - 1)))
                {
                    index[n] = i;

                    n++;
                }
            }

            // select a random not-downloaded file part to download

            Random random = new Random();

            if (n > 0)
            {
                while (true)
                {
                    int a = 0;

                    if (download.RemainingFileParts != 0)
                    {
                        a = random.Next(n);

                        if (download.ListFileParts[index[a]] != 0)
                        {
                            // start to download the file part

                            string[] Params = new string[3];
                            Params[0] = download.Name;
                            Params[1] = download.SHA1;
                            Params[2] = (index[a] * 16384).ToString();

                            Messages.IMessage FprMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.FPR, Params);

                            Peer.Send(FprMess);

                            return(true);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #3
0
 protected override void ProcessMessage(Messages.IMessage message)
 {
     base.ProcessMessage(message);
     if (message.Action == (byte)GameMessageCodes.RemovePeerFromGame)
     {
         this.onRemovePlayerEvent.Set();
     }
 }
Exemple #4
0
 public void Broadcast(Messages.IMessage message)
 {
     lock (ReceiversLock)
     {
         foreach (Receiver receiver in Receivers)
         {
             receiver.SendMessage(message);
         }
     }
 }
Exemple #5
0
        private void SendDataAsync(WebSocket socket, Messages.IMessage message)
        {
            using (var buffer = bufferManager.GetBuffer())
            {
                int msgLen = message.ToBytes(buffer.Buffer);

                socket.SendAsync(new Memory <byte>(buffer.Buffer, 0, msgLen), WebSocketMessageType.Binary, true, CancellationToken.None);

                Interlocked.Add(ref bytesSent, msgLen);
            }
        }
Exemple #6
0
 public void Send(Messages.IMessage msg)
 {
     try
     {
         msg.Endpoint = this.EndPoint;
         this.Client.Send(msg);
     }
     catch (Exception ex)
     {
         Logger.Logger.LogException(ex);
     }
 }
 public string PushErrorMessage(Messages.IMessage input)
 {
     try
     {
         SendToDb(input);
         return("The following error description saved in DB : - " + input.ErrorDescription);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Exemple #8
0
        public async Task Handle(FortData gym)
        {
            if (!gymStatus.ContainsKey(gym.Id))
            {
                var gymDetailsResponse = await GetGymDetails(gym);

                if (gymDetailsResponse != null)
                {
                    var gymDetails = new GymDetails(gym, gymDetailsResponse.Name, gymDetailsResponse.ImageUrls.FirstOrDefault(), pogoInstance.Configuration.Name);

                    pogoInstance.Database.AddGymDetails(gymDetails);
                    gymStatus.Add(gym.Id, gymDetails);
                }
            }
            else
            {
                var gymDetails = gymStatus[gym.Id];

                bool isInBattle      = gym.IsInBattle && !gymDetails.IsInBattle;
                bool isNowNeutral    = gym.OwnedByTeam == TeamColor.Neutral && gymDetails.Owner != TeamColor.Neutral;
                bool hasChangedOwner = gym.OwnedByTeam != gymDetails.Owner;

                gymDetails.Update(gym);
                pogoInstance.Database.UpdateGymDetails(gymDetails);

                Messages.IMessage message = null;
                if (isInBattle)
                {
                    if (!pogoInstance.Configuration.IgnoreGymUnderAttack)
                    {
                        log.Info($"Gym, {gymDetails.Name}, is under attack");
                        message = new GymUnderAttackMessage(gymDetails, pogoInstance.Configuration);
                    }
                }
                else if (isNowNeutral)
                {
                    log.Info($"Gym, {gymDetails.Name}, is now neutral");
                    message = new GymNeutralMessage(gymDetails, pogoInstance.Configuration);
                }
                else if (hasChangedOwner)
                {
                    log.Info($"Gym, {gymDetails.Name}, has been taken by {gymDetails.Owner.ToTeamName()}");
                    message = new GymHasBeenTakenMessage(gymDetails, pogoInstance.Configuration);
                }

                if (message != null)
                {
                    message.Send();
                }
            }
        }
        internal CommandSaga(IMessageHandlerContext context, string sagaId, Messages.IMessage originating, string domainDestimation)
        {
            _context           = context;
            _sagaId            = sagaId;
            _originating       = originating;
            _domainDestination = domainDestimation;
            _commands          = new List <Messages.ICommand>();
            _abortCommands     = new List <Messages.ICommand>();

            if (string.IsNullOrEmpty(_domainDestination))
            {
                throw new ArgumentException($"Usage of SAGA needs a domain destination or specify Configuration.SetCommandDestination");
            }
        }
        private static void SendToDb(Messages.IMessage input)
        {
            var storagedatatable = new DataTable();

            storagedatatable.Columns.Add("Id", typeof(int));
            storagedatatable.Columns.Add("ErrorDescription", typeof(string));
            if (input.MsgType == "ERR")
            {
                //Save to the table
                var newrow = storagedatatable.NewRow();
                newrow["ErrorDescription"] = input.ErrorDescription;
                storagedatatable.Rows.Add(newrow);
            }
        }
Exemple #11
0
        private void BroadcastMessage(Messages.IMessage message)
        {
            using (var buffer = bufferManager.GetBuffer())
            {
                int msgLen = message.ToBytes(buffer.Buffer);
                var mem    = new Memory <byte>(buffer.Buffer, 0, msgLen);

                foreach (var player in Players)
                {
                    player.Value.Socket.SendAsync(mem, WebSocketMessageType.Binary, true, CancellationToken.None);
                    Interlocked.Add(ref bytesSent, msgLen);
                }
            }
        }
Exemple #12
0
        public void Handle(FortData gym)
        {
            if (!cachedGyms.ContainsKey(gym.Id))
            {
                cachedGyms.Add(gym.Id, new CachedGymData {
                    GymData = gym
                });
            }
            else
            {
                var cachedData = cachedGyms[gym.Id];

                if (cachedData.GymDetails == null)
                {
                    cachedData.GymDetails = GetGymDetails(gym);
                    if (cachedData.GymDetails == null)
                    {
                        return;
                    }
                }

                Messages.IMessage message = null;
                if (gym.IsInBattle && !cachedData.GymData.IsInBattle)
                {
                    message = new GymUnderAttackMessage(gym, cachedData.GymDetails, pogoInstance.Configuration);
                }
                else if (gym.OwnedByTeam == TeamColor.Neutral && cachedData.GymData.OwnedByTeam != TeamColor.Neutral)
                {
                    message = new GymNeutralMessage(gym, cachedData.GymDetails, pogoInstance.Configuration);
                }
                else if (gym.OwnedByTeam != cachedData.GymData.OwnedByTeam)
                {
                    message = new GymHasBeenTakenMessage(gym, cachedData.GymDetails, pogoInstance.Configuration);
                }

                if (message != null)
                {
                    message.Send();
                }

                cachedData.GymData = gym;
            }
        }
Exemple #13
0
        /// <summary>
        /// Send a new FPR to the peer for download the next not-downloaded file pack of a this file part.
        /// </summary>
        /// <param name="filePackNum">The number of the file pack.</param>
        /// <param name="filePartNum">The number of the file part.</param>
        /// <param name="download">The download object.</param>
        /// <param name="Peer">The IP address of peer to send the FPR message.</param>
        /// <returns>Return true if the message has been sended; return false if the file part is completed.</returns>
        private static bool DownloadNextFilePackOfAFilePart(int filePackNum, int filePartNum, Objects.Download download, Objects.Peer Peer)
        {
            int nPack   = filePackNum;
            int partEnd = (filePartNum * 128) + 128;

            for (int i = 0; i < 128; i++)
            {
                if (nPack < download.ListFilePacks.Length)
                {
                    if (download.ListFilePacks[nPack] == false)
                    {
                        // download this file pack

                        string[] Params = new string[3];
                        Params[0] = download.Name;
                        Params[1] = download.SHA1;
                        Params[2] = (nPack * 16384).ToString();

                        Messages.IMessage FprMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.FPR, Params);

                        Peer.Send(FprMess);

                        return(true);
                    }
                }
                else
                {
                    return(false);
                }

                if (nPack < partEnd)
                {
                    nPack++;
                }
                else
                {
                    nPack = filePartNum * 128;
                }
            }

            return(false);
        }
Exemple #14
0
        public override void sendMsg(Messages.IMessage message)
        {
            if (port == null || !port.IsOpen)
            {
                throw new DeviceNotConnectedException("tried to send data while the device is not connected!");
            }

            zUpMessage m = message as zUpMessage;

            log.Info("sending " + m.ToString());

            foreach (char c in m.asCharArray())
            {
                port.Write(c.ToString());
                System.Threading.Thread.Sleep(100);
            }

            //port.Write(m.asCharArray(), 0, m.asCharArray().Length);
            System.Threading.Thread.Sleep(100);
        }
Exemple #15
0
        /// <summary>
        /// Send a message to a peer still connected ( USE THIS FOR SENDING MESSAGE WITH BINARY PARTS )
        /// </summary>
        /// <param name="IMessage">Message in IMessage interface.</param>
        /// <param name="PeerIP">IP:Port</param>
        /// <returns>If return False the sending is failed.</returns>
        public static void Send(Messages.IMessage IMessage, string PeerIP)
        {
            byte[] Message_Byte = IMessage.MessageByte;

            PeersList.Peer peer = PeersList.GetPeerByIP(PeerIP);

            try
            {
                NetworkStream stream = peer.Client.GetStream();
                stream.Write((byte[])Message_Byte, 0, ((byte[])Message_Byte).Length);
            }
            catch
            {
                // remove the peer
                PeersList.RemovePeer(PeerIP);

                Debug.WriteLine("A message hasn't been sent, probably the peer is offline or disconnected", "Error");

                //MessageBox.Show("ERROR: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // DEBUG
            }
        }
        public string PushNormalMessage(Messages.IMessage input)
        {
            const string url      = "http://localhost:62852/api/values";
            var          response = string.Empty;

            try
            {
                using (var client = new WebClient())                     //WebClient
                {
                    client.Headers.Add("Content-Type:application/json"); //Content-Type
                    client.Headers.Add("Accept:application/json");
                    var serializedData = JsonConvert.SerializeObject(input);
                    response = client.UploadString(url, serializedData);
                }

                return(response);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Exemple #17
0
        /// <summary>
        /// Search a single file, automatic searching and sending FS messages.
        /// </summary>
        /// <param name="FileName">The name of the file to search.</param>
        public static void SearchFile(string FileName)
        {
            // save the name of the file to search
            LastSearch = FileName;

            // number of sent messages
            int nMess = 0;

            // number of messages to send
            int max = Global.NumberFSMessagesForSearch;

            // the FS-message
            Messages.IMessage FsMessage = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.FS, Global.TtlMessage, (Global.MyRemoteIP + ":" + Global.ListeningPort), FileName);

            for (int i = 0; i < Lists.PeersList.List.Count; i++)
            {
                if (nMess >= max)
                {
                    break;
                }

                // control if there are enough peers for send all the messages
                if ((Lists.PeersList.List.Count - i) > (max - nMess))
                {
                    if (Lists.PeersList.List[i].HasFileByName(FileName))
                    {
                        Lists.PeersList.List[i].Send(FsMessage);
                        nMess++;
                    }
                }
                else
                {
                    Lists.PeersList.List[i].Send(FsMessage);
                    nMess++;
                }
            }
        }
 public SagaWasAborted(Messages.IMessage original)
 {
     Originating = original;
 }
Exemple #19
0
        /// <summary>
        /// Send a Tcp connection request to a new peer.
        /// </summary>
        /// <param name="Message">The request message.</param>
        /// <param name="PeerIP">The IP address of the new peer [IP:Port].</param>
        public static void SendConnectionRequest(string Message, string PeerIP)
        {
            Thread t = new Thread(new ParameterizedThreadStart(
                                      delegate
            {
                // converts UTF16 to Byte[]

                byte[] MessageByte = ASCIIEncoding.Unicode.GetBytes(Message);

                TcpClient client = new TcpClient();

                NetworkStream stream = null;

                try
                {
                    string[] subPeerIP = PeerIP.Split(':');

                    string ip = subPeerIP[0];

                    int port = int.Parse(subPeerIP[1]);

                    // control the peer ip
                    ControlPeerIPAddress(ref ip, port);

                    // connect to peer
                    client = new TcpClient();

                    client.Connect(ip, port);

                    // get stream
                    stream = client.GetStream();

                    // send the request
                    stream.Write(MessageByte, 0, MessageByte.Length);

                    Global.CountUploadRate += MessageByte.Length;

                    // wait a reply
                    System.Timers.Timer timer = new System.Timers.Timer(15000);

                    timer.Elapsed += new ElapsedEventHandler(delegate { Thread.CurrentThread.Abort(); });

                    timer.Enabled = true;

                    byte[] reply_message_byte = new byte[3072];

                    byte[] bytes = new byte[3072];

                    stream.Read(reply_message_byte, 0, reply_message_byte.Length);

                    int i = 0;
                    int num_bytes_read = 0;

                    do
                    {
                        if (stream.DataAvailable)
                        {
                            stream.Read(bytes, 0, bytes.Length);
                            Array.Copy(bytes, 0, reply_message_byte, num_bytes_read, i);
                            num_bytes_read += i;
                        }
                        else
                        {
                            Thread.Sleep(10);

                            if (!stream.DataAvailable)
                            {
                                break;
                            }

                            i = 1;
                        }
                    } while (i != 0);

                    timer.Stop();

                    string reply = ASCIIEncoding.Unicode.GetString(reply_message_byte);

                    string[] sub_reply = reply.Split('\n');

                    // if the peer have accepted the connection request
                    if (sub_reply[0].Substring(0, 4) == "Nova" && sub_reply[1].Substring(0, 10) == "CONNECT_OK")
                    {
                        Utilities.Log.Write("Connection established with " + PeerIP, Utilities.Log.LogCategory.ConnectionRequests);

                        // create a new peer object
                        Objects.Peer peer = new Objects.Peer(PeerIP, client, stream);
                        peer.ID           = "EMPTY";

                        // send a EI-message

                        string eiMessParam1;
                        string eiMessParam2;

                        if (Global.MessageEncryptionEnabled == true)
                        {
                            eiMessParam1 = "y";
                            eiMessParam2 = string.Format("{0},{1}",
                                                         Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.N),
                                                         Utilities.Converterer.ConvertByteToHex(peer.MyAsymmetricEncryptionKey.E));
                        }
                        else
                        {
                            eiMessParam1 = "n";
                            eiMessParam2 = string.Empty;
                        }

                        // create and send a EI-message

                        Messages.IMessage eiMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.EI, false, eiMessParam1, eiMessParam2);

                        peer.Send(eiMess);

                        // add the peer in the list of the peers
                        Lists.PeersList.AddPeer(peer);
                    }
                    else
                    {
                        stream.Close();
                        client.Close();
                    }

                    timer.Close();
                }
                catch
                {
                    if (client != null)
                    {
                        client.Close();
                    }
                    if (stream != null)
                    {
                        stream.Close();
                    }

                    Utilities.Log.Write("The connection request hasn't been sent, probably the peer (" + PeerIP + ") is offline or disconnected", Utilities.Log.LogCategory.Error);
                }
            }));

            t.Name         = "MessageSender_Connection_Request_Sending";
            t.IsBackground = true;
            t.Start();
        }
Exemple #20
0
 public void Send(Messages.IMessage msg)
 {
     msg.Endpoint = this.EndPoint;
     this.Client.Send(msg);
 }
Exemple #21
0
 public void SendMessage(Messages.IMessage message)
 {
     MessageQueue.Add(message);
 }
Exemple #22
0
        /// <summary>
        /// Process a serie of messages.
        /// </summary>
        /// <param name="MessagesByte">The messages to process.</param>
        /// <returns>If returns NULL the messages was completed instead returns the incompleted message.</returns>
        private byte[] ProcessMessages(byte[] MessagesByte)
        {
            try
            {
                #region control if there is a single message or more, and control if the message ( the command only ) is correct

                // list of commands
                string[] commandsList = { "FS\n", "FF\n", "FPR", "FP\n", "PI\n", "PO\n", "XLR", "XL\n", "EI\n", "EK\n" };

                // the start of the message ( in byte )
                int messagePointer = 0;

                // the number of '\n' chars found in a single message
                int n = 0;

                // the command of the message
                string commandMess = string.Empty;

                bool commandCorrect = false;

                // the start of the length of the parameters
                int startLength = 0;

                // the start of the parameters
                int startParameters = 0;

                // the length of the parameters
                int parametersLength = 0;

                // the end of this single message ( in byte )
                int endSingleMessage = 0;

                while (true)
                {
                    #region ...

                    if ((messagePointer + 6) < MessagesByte.Length)
                    {
                        commandCorrect = false;

                        // get the first 3 char of the message for get the command of it
                        commandMess = ASCIIEncoding.Unicode.GetString(MessagesByte, messagePointer, 6);                         // unicode 2 byte for char ( 3 chars = 2*3 = 6 bytes )

                        // control if the gotten command is correct or not
                        for (int j = 0; j < commandsList.Length; j++)
                        {
                            if (commandMess == commandsList[j])
                            {
                                commandCorrect = true;

                                break;
                            }
                        }

                        if (commandCorrect == true)
                        {
                            #region

                            n = 0;

                            // get the length of the parameters of this message
                            for (int b = messagePointer + 8; b < MessagesByte.Length; b += 2)
                            {
                                if (ASCIIEncoding.Unicode.GetString(MessagesByte, b, 2) == "\n")
                                {
                                    n++;

                                    // the start of the length of the parameters
                                    if (n == 3)
                                    {
                                        startLength = b + 2;
                                    }

                                    // the finish of the length of the parameters
                                    if (n == 4)
                                    {
                                        startParameters = b + 2;

                                        if (startLength + (startParameters - startLength - 2) <= MessagesByte.Length)
                                        {
                                            parametersLength = int.Parse(ASCIIEncoding.Unicode.GetString(MessagesByte, startLength, (startParameters - startLength - 2)));

                                            endSingleMessage = startParameters + parametersLength - 1;

                                            break;
                                        }
                                        else                                         // the message isn't complete
                                        {
                                            return(MessagesByte);
                                        }
                                    }
                                }
                            }

                            // control if the message is not complete
                            if (n != 4)
                            {
                                return(MessagesByte);
                            }

                            // get the single message from message_byte

                            // control if the message is completed or not
                            if ((MessagesByte.Length - endSingleMessage) > 0)
                            {
                                # region process the single message

                                byte[] singleMessage = new byte[(endSingleMessage - messagePointer + 1)];

                                Array.Copy(MessagesByte, messagePointer, singleMessage, 0, singleMessage.Length);

                                // process the single message

                                Thread t1 = new Thread(new ParameterizedThreadStart(
                                                           delegate
                                {
                                    Messages.IMessage message = Messages.MessagesFactory.Instance.ParseMessage(singleMessage, this);

                                    if (message != null)
                                    {
                                        // control if the message has already been processed time ago
                                        if ((message.MessageType != Messages.Commands.FS.ToString()) || !Lists.MessageIDsList.CheckAndAddID(message.ID))
                                        {
                                            // process the message
                                            message.Process();

                                            Utilities.Log.Write("New " + message.MessageType + " from " + this.IP, Utilities.Log.LogCategory.InputMessages);
                                        }
                                        else
                                        {
                                            Utilities.Log.Write(message.MessageType + " from " + this.IP + " has already been processed", Utilities.Log.LogCategory.InputMessages);
                                        }
                                    }
                                }));

                                t1.Name = "StreamChecker_GetAndProcessMessage";
                                t1.Start();

                                // update charPointer
                                messagePointer = endSingleMessage + 1;

                                #endregion
                            }
                            else                             // the message is not completed and need waits a new data-block
                            {
                                // get the incompleted message
                                byte[] incompletedMessage = new byte[(MessagesByte.Length - messagePointer)];

                                Array.Copy(MessagesByte, messagePointer, incompletedMessage, 0, incompletedMessage.Length);

                                return(incompletedMessage);
                            }

                            #endregion
                        }
                        else
                        {
                            Utilities.Log.Write("Invalid input message from " + this.IP, Utilities.Log.LogCategory.InputMessages);

                            return(null);
                        }
                    }
                    else if (messagePointer == MessagesByte.Length)
                    {
                        return(null);
                    }
                    else
                    {
                        return(MessagesByte);
                    }

                    #endregion
                }
Exemple #23
0
        public void Send(Messages.IMessage message, bool blocking)
        {
            var frame = message.Encode();

            this.FChannel.Send(frame, blocking);
        }
Exemple #24
0
 public override IResponse sendRecieve(Messages.IMessage message)
 {
     throw new NotImplementedException();
 }
Exemple #25
0
        // spesified the message that can be handle by this protocol

        // we have a state here

        public void Handle(Messages.IMessage message)
        {
            // we can attach the message processor to processs the message that can process parallel

            throw new NotImplementedException();
        }
 public SagaAbortionFailureException(Messages.IMessage originating) :
     base("Failed to run abort commands for saga")
 {
     Originating = originating;
 }
Exemple #27
0
        private void ReceivingMethod()
        {
            byte[] frame         = new byte[4];
            int    framePosition = 0;
            int    frameSize     = 0;

            byte[] data         = new byte[0];
            int    dataPosition = 0;

            while (Connected)
            {
                if (Client.Available > 0)
                {
                    TotalBytesUsage += Client.Available;

                    try
                    {
                        NetworkStream stream   = Client.GetStream();
                        byte[]        inbuffer = new byte[Client.ReceiveBufferSize];

                        if (stream.CanRead)
                        {
                            do
                            {
                                if (framePosition < 3)
                                {
                                    int bytesRead = stream.Read(frame, framePosition, 4 - framePosition);
                                    framePosition = framePosition + bytesRead;

                                    if (framePosition > 3)
                                    {
                                        frameSize |= frame[0];
                                        frameSize |= (((int)frame[1]) << 8);
                                        frameSize |= (((int)frame[2]) << 16);
                                        frameSize |= (((int)frame[3]) << 24);

                                        if (frameSize > MaxMessageSize)
                                        {
                                            Disconnect();
                                            break;
                                        }

                                        if (frameSize == 0) // Heartbeat
                                        {
                                            frame         = new byte[4];
                                            framePosition = 0;
                                        }

                                        // reset data
                                        data         = new byte[frameSize];
                                        dataPosition = 0;
                                    }
                                }
                                else
                                {
                                    int bytesRead = stream.Read(data, dataPosition, frameSize - dataPosition);
                                    dataPosition = dataPosition + bytesRead;

                                    if (dataPosition >= frameSize)
                                    {
                                        Messages.IMessage message = Server.SerializationEngine.Deserialize(data);

                                        if (message is Messages.Disconnect)
                                        {
                                            Disconnect();
                                            break;
                                        }

                                        // global message dispatcher
                                        if (Server.GetMessageDispatchers().ContainsKey(message.GetType()))
                                        {
                                            Server.GetMessageDispatchers()[message.GetType()].Dispatch(message, this);
                                        }

                                        // local message dispatcher
                                        if (_messageDispatchers.ContainsKey(message.GetType()))
                                        {
                                            _messageDispatchers[message.GetType()].Dispatch(message, this);
                                        }

                                        // reset frame and data
                                        frame         = new byte[4];
                                        framePosition = 0;
                                        frameSize     = 0;

                                        data         = new byte[0];
                                        dataPosition = 0;
                                    }
                                }
                            } while (stream.DataAvailable);
                        }
                    }
                    catch (Exception)
                    {
                        Disconnect();
                    }
                }

                Thread.Sleep(ReceivingInterval);
            }
        }
Exemple #28
0
        /// <summary>
        /// Logs a downloaded file pack and send a new FPR message if is necessary.
        /// </summary>
        /// <param name="Download">The download object.</param>
        /// <param name="StartPoint">The star point of the file pack.</param>
        /// <param name="SenderPeer">The sender peer object.</param>
        /// <param name="Status">If the file-pack has been written or not ( other ).</param>
        public static void LogFilePack(Objects.Download Download, int StartPoint, Objects.Peer SenderPeer, Status_FilePack Status)
        {
            // indicate the downloading of a file pack
            SenderPeer.FilePackDownloaded = true;

            if (Status == Status_FilePack.Written)
            {
                #region ...

                int filePackNum = StartPoint / 16384;
                int filePartNum = StartPoint / 2097152;

                // control if the file pack is already been downloaded
                if (Download.ListFilePacks[filePackNum] == false)
                {
                    // update the list of file packs
                    Download.ListFilePacks[filePackNum] = true;

                    // update the number of remaining file packs
                    Download.RemainingFilePacks--;

                    // update the list of file parts
                    Download.ListFileParts[filePartNum]--;

                    // control if the file part is completed
                    if (Download.ListFileParts[filePartNum] == 0)
                    {
                        // update the number of remaining file parts
                        Download.RemainingFileParts--;

                        // control if the download is finished
                        if (Download.RemainingFilePacks == 0)
                        {
                            // move the completed download from temp-directory to shared-directory
                            File.Move(Global.TempDirectory + Download.Name, Global.SharedDirectory + Download.Name);

                            // update download's informations
                            Download.Progress = 100;
                            Download.Active   = false;
                        }
                        else
                        {
                            // send a new FPR to the peer for the next not downloaded file pack of a new file part
                            StartDownloadNextFilePart(Download, SenderPeer);
                        }
                    }
                    else
                    {
                        // send a new FPR to the peer for the next not downloaded file pack of a this file part
                        if (DownloadNextFilePackOfAFilePart(filePackNum, filePartNum, Download, SenderPeer) == false)
                        {
                            StartDownloadNextFilePart(Download, SenderPeer);
                        }
                    }

                    // log the file pack
                    Download.LogFilePack(SenderPeer.IP, filePackNum);

                    NewOrUpdatedDownload = true;
                }

                #endregion
            }

            // if the FilePack is damaged, will send a new FPR-mess to the peer;
            else if (Status == Status_FilePack.Damaged)
            {
                #region ...

                string[] Params = new string[3];
                Params[0] = Download.Name;
                Params[1] = Download.SHA1;
                Params[2] = StartPoint.ToString();

                Messages.IMessage FprMess = Messages.MessagesFactory.Instance.CreateMessage(Messages.Commands.FPR, Params);

                SenderPeer.Send(FprMess);

                #endregion
            }
        }
Exemple #29
0
 /// <summary>
 /// Sends a message to the peer.
 /// </summary>
 /// <param name="Message">Message to send.</param>
 public void Send(Messages.IMessage Message)
 {
     this.m_listMessagesToWrite.Add(Message);
 }