GlowCommon.CommandServer.SendMessage C# (CSharp) Method

SendMessage() public method

Can be called by the client to send a message.
public SendMessage ( Command cmd ) : Task
cmd GlowCommon.DataObjects.Command Message to be sent
return Task
        public async Task<bool> SendMessage(Command cmd)
        {
            if(m_mode == CommmandServerMode.Server)
            {
                throw new NotImplementedException("Server can't send message right now");
            }

            if(m_socket == null && m_clientDataWriter != null)
            {
                throw new Exception("The socket isn't open!");
            }

            lock(m_commandQueue)
            {
                // Add the command to the queue
                m_commandQueue.Enqueue(cmd);

                // Check to see if we should send 
                if (m_isSendingCommand)
                {
                    // If we are already sending just add the command to be sent later.                    
                    return true;
                }
                else
                {
                    // If we are not sending we need to send.
                    m_isSendingCommand = true;
                }
            }

            while (true)
            {
                // Grab the next command to send.
                Command currentCommand = null;
                lock (m_commandQueue)
                {
                    if (m_commandQueue.Count == 0)
                    {
                        m_isSendingCommand = false;
                        return true;
                    }
                    currentCommand = m_commandQueue.Dequeue();
                }

                // Try to send it.
                try
                {
                    await InternalSendMessage(currentCommand, m_clientDataWriter);
                }
                catch (Exception e)
                {
                    // We failed, tell the consumer.
                    System.Diagnostics.Debug.WriteLine("Send Message Failed: " + e.Message);
                    m_socket = null;
                    m_clientDataWriter = null;
                    m_listener.OnDisconnected();
                    return false;
                }
            }
        }

Usage Example

Example #1
0
        /// <summary>
        /// Called by the consumer when they want to send a message to the other side.
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public async Task <bool> SendCommand(Command cmd)
        {
            lock (objectLock)
            {
                if (!IsConnected || m_commandServer == null)
                {
                    return(false);
                }
            }

            // Send the message
            return(await m_commandServer.SendMessage(cmd));
        }