我的异步 tcp 客户端-服务器应用程序现在正在运行。
但是我有一些 CPU 重负载问题。如果我将网络缓冲区设置为 8192,它适用于小消息,但如果我传输超过 1MB,我的 CPU 负载真的很高。我可以通过将缓冲区设置为 81920 来修复它。
有什么解决方案可以解决这个问题吗?我想将数据从几 KB 传输到数百 MB。
拥有多个不同缓冲区大小的 TCP 连接是个好主意吗?还有其他解决方案吗?
我的代码也可能存在一些性能问题。
我的阅读代码:
private class ReadClientState
{
public TcpClient Client { get; set; }
public byte[] Buffer { get; set; } // buffer size...???
public byte[] inc_message { get; set; }
public int inc_message_size { get; set; }
}
开始读取回调:
private void ReadCallback(IAsyncResult ar)
{
ReadClientState state = (ReadClientState)ar.AsyncState;
int cbRead = 0;
try
{
cbRead = state.Client.GetStream().EndRead(ar);
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException is SocketException)
{
if (((SocketException)ex.InnerException).ErrorCode == 10054)
{
...
}
}
return;
}
// read 4 byte lenght header (new message incoming)
if (state.inc_message_size == 0)
{
byte[] header = new byte[4];
Buffer.BlockCopy(state.Buffer, 0, header, 0, 4);
state.inc_message_size = BitConverter.ToInt32(header, 0);
}
// copy buffer to message data array
byte[] tmp = new byte[cbRead];
Buffer.BlockCopy(state.Buffer, 0, tmp, 0, cbRead);
state.inc_message = state.inc_message.Concat(tmp).ToArray();
state.Buffer = new byte[bufferSize];
Array.Clear(state.Buffer, 0, state.Buffer.Length);
// message is complete
if (state.inc_message.Length >= state.inc_message_size)
{
if (state.inc_message.Length > state.inc_message_size)
{
Console.WriteLine("ERROR.. read more than expected");
}
else
{
Console.WriteLine("massage size: " + state.inc_message_size.ToString() + " total bytes read: " + state.inc_message.Length.ToString());
Array.Clear(state.inc_message, 0, state.inc_message.Length);
state.inc_message_size = 0;
}
}
try
{
state.Client.GetStream().BeginRead(state.Buffer, 0, state.Buffer.Length, ReadCallback, state);
}
catch (Exception ex)
{
return;
}
}