Ejemplo n.º 1
0
        /// <summary>
        /// Set and send the object of this message.
        /// </summary>
        /// <param name="clientSocket">The socket to send the data through.</param>
        /// <param name="obj">The object to send.</param>
        /// <param name="context">The context needed to send the broadcast.</param>
        /// <remarks>Depending on the current message type, only one object type will be supported.</remarks>
        public void Send(Socket clientSocket, Context context)
        {
            var    formatter    = new BinaryFormatter();
            string intentAction = MessageType.GetIntentAction(true);

            // First send the message type.
            byte[] buffer = new byte[1];
            buffer[0] = (byte)MessageType;
            clientSocket.SendBufferSize = buffer.Length;
            clientSocket.Send(buffer);

            // Then send the object length (in bytes) if the message is carrying data.
            if (IsCarryingData)
            {
                buffer = BitConverter.GetBytes(Length);
                clientSocket.SendBufferSize = buffer.Length;
                clientSocket.Send(buffer);

                using (MemoryStream ms = new MemoryStream())
                {
                    formatter.Serialize(ms, Data);
                    buffer = ms.ToArray();
                    for (int i = 0; i < buffer.Length;)
                    {
                        clientSocket.SendBufferSize = Step;
                        i += clientSocket.Send(buffer, i, Step, SocketFlags.None);
                        Intent progressIntent = new WifiP2pMessageIntent(intentAction, (float)i / buffer.Length, false, this);
                        context.SendBroadcast(progressIntent);
                    }
                }
            }

            // Broadcast completion.
            Intent doneIntent = new WifiP2pMessageIntent(intentAction, 1, true, this);

            context.SendBroadcast(doneIntent);
        }