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;
}
}
}