public void sendOutgoingMessages()
{
try
{
if (queuedOutMessages.Count > 0)
{
//Check the size of the next message
byte[] next_message = null;
int send_buffer_index = 0;
byte[] send_buffer = new byte[SEND_BUFFER_SIZE];
while (queuedOutMessages.TryPeek(out next_message))
{
if (send_buffer_index == 0 && next_message.Length >= send_buffer.Length)
{
//If the next message is too large for the send buffer, just send it
queuedOutMessages.TryDequeue(out next_message);
tcpClient.GetStream().BeginWrite(
next_message,
0,
next_message.Length,
asyncSend,
next_message);
}
else if (next_message.Length <= (send_buffer.Length - send_buffer_index))
{
//If the next message is small enough, copy it to the send buffer
queuedOutMessages.TryDequeue(out next_message);
next_message.CopyTo(send_buffer, send_buffer_index);
send_buffer_index += next_message.Length;
}
else
{
//If the next message is too big, send the send buffer
tcpClient.GetStream().BeginWrite(
send_buffer,
0,
send_buffer_index,
asyncSend,
next_message);
send_buffer_index = 0;
send_buffer = new byte[SEND_BUFFER_SIZE];
}
}
//Send the send buffer
if (send_buffer_index > 0)
{
tcpClient.GetStream().BeginWrite(
send_buffer,
0,
send_buffer_index,
asyncSend,
next_message);
}
}
}
catch (System.InvalidOperationException) { }
catch (System.IO.IOException) { }
}