我想优化TCP套接字包装物,有很多的入站连接的挣扎。我在一个基本的聊天服务器和一个小客户端应用程序中测试它,以便将客户端发送给它。这两个应用程序都位于由千兆交换机连接的单独的W2k3服务器上。Socket.SendAsync服用几秒钟完成
通过试验和错误,我改进我的测试,以10个客户在100周毫秒的时间间隔连接,那么一旦所有10个连接它们每一个发送达到100MS间隔“入室”消息给服务器,再一次。当服务器收到一条消息时,它会向房间中的每个人列表回复发件人,并向房间中的其他人发送消息,告诉他们新的到来。
每个发送都需要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();
}
你能发表一些相关的代码吗?猜测套接字问题是非常困难的。 – 2010-10-01 16:37:40
你有一个SocketAsyncEventArgs池吗? – 2010-10-01 19:59:28
埃里克 - 我目前没有汇集SocketAysncEventArgs,但计划稍后添加。不过,我在创建SocketAysncEventArgs并填充其缓冲区并将结束时间记录为回调中的第一个操作之后记录了开始时间,因此,虽然我知道它的低效率,但它不应该影响此部分执行? – Adster 2010-10-04 09:24:44