我正在尝试优化 TCP 套接字包装器,该包装器正在处理大量入站连接。我正在一个基本的聊天服务器和一个小型客户端应用程序中测试它,以将客户端发送到它。这两个应用程序都位于通过千兆位交换机连接的单独 W2k3 服务器上。
通过反复试验,我将测试改进为 10 个客户端以 100 毫秒的间隔连接,然后一旦所有 10 个客户端都连接起来,它们都会向服务器发送一条“进入房间”消息,同样以 100 毫秒的间隔。当服务器收到消息时,它会用房间中每个人的列表回复发送者,并向房间中的其他每个人发送一条消息,表示有新消息到达。
每次发送都需要 1 秒多的时间才能完成(对于 100 多个客户端,这个时间会长达 3-4 秒),并且通过日志记录,我已经确定延迟发生在 Socket.SendAync 和引发的相应事件之间。 CPU 使用率始终保持在较低水平。
我已经尝试了我能想到的一切,并花了几天时间在网上寻找线索,但我完全不知所措。这不可能是正常的吧?
编辑:按要求编码。我已经对其进行了一些整理,删除了不相关的计数器和日志记录等,当我试图缩小问题范围时,它目前在黑客之上的黑客之上。
private void DoSend(AsyncUserToken token, String msg)
{
SocketAsyncEventArgs writeEventArgs = new SocketAsyncEventArgs();
writeEventArgs.Completed += ProcessSend;
writeEventArgs.UserToken = token;
Byte[] sendBuffer = Encoding.UTF8.GetBytes(msg + LineTerminator);
writeEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
Interlocked.Add(ref m_totalBytesAttemptedSend, sendBuffer.Length);
Logger2.log(Logger2.Debug5, token.ConnectionId, "Total Bytes attempted: " + m_totalBytesAttemptedSend);
bool willRaiseEvent = true;
try
{
willRaiseEvent = token.Socket.SendAsync(writeEventArgs);
}
catch (Exception e)
{
Logger2.log(Logger2.Debug2, token.ConnectionId, e.Message);
writeEventArgs.Dispose();
}
if (!willRaiseEvent)
{
ProcessSend(null, writeEventArgs);
}
}
private void ProcessSend(Object sender, SocketAsyncEventArgs e)
{
AsyncUserToken token = (AsyncUserToken)e.UserToken;
Logger2.log(Logger2.Debug5, token.ConnectionId, "Send Complete");
if (e.SocketError == SocketError.Success)
{
Interlocked.Add(ref m_totalBytesSent, e.BytesTransferred);
Logger2.log(Logger2.Debug5, ((AsyncUserToken)e.UserToken).ConnectionId, "Total Bytes sent: " + m_totalBytesSent);
}
else
{
if (token.Connected)
{
CloseClientSocket(token);
}
}
e.Dispose();
}