我有一些网络代码来处理任意 TCP 连接。
这一切似乎都按预期工作,但似乎很慢。当我分析代码时,它似乎在 NetworkStream.Read() 中花费了 600 毫秒,我想知道如何改进它。我已经摆弄了缓冲区大小,并在一个巨大的缓冲区之间交替读取所有数据,或者一个小的缓冲区应该将数据连接到一个 StringBuilder 中。目前我使用的客户端是一个网络浏览器,但是这段代码是通用的,它很可能不是发送给它的 HTTP 数据。有任何想法吗?
我的代码是这样的:
public void StartListening()
{
try
{
lock (oSyncRoot)
{
oTCPListener = new TcpListener(oIPaddress, nPort);
// fire up the server
oTCPListener.Start();
// set listening bit
bIsListening = true;
}
// Enter the listening loop.
do
{
// Wait for connection
TcpClient newClient = oTCPListener.AcceptTcpClient();
// queue a request to take care of the client
oThreadPool.QueueUserWorkItem(new WaitCallback(ProcessConnection), newClient);
}
while (bIsListening);
}
catch (SocketException se)
{
Logger.Write(new TCPLogEntry("SocketException: " + se.ToString()));
}
finally
{
// shut it down
StopListening();
}
}
private void ProcessConnection(object oClient)
{
TcpClient oTCPClient = (TcpClient)oClient;
try
{
byte[] abBuffer = new byte[1024];
StringBuilder sbReceivedData = new StringBuilder();
using (NetworkStream oNetworkStream = oTCPClient.GetStream())
{
// set initial read timeout to nInitialTimeoutMS to allow for connection
oNetworkStream.ReadTimeout = nInitialTimeoutMS;
int nBytesRead = 0;
do
{
try
{
bool bDataAvailable = oNetworkStream.DataAvailable;
while (!bDataAvailable)
{
Thread.Sleep(5);
bDataAvailable = oNetworkStream.DataAvailable;
}
nBytesRead = oNetworkStream.Read(abBuffer, 0, abBuffer.Length);
if (nBytesRead > 0)
{
// Translate data bytes to an ASCII string and append
sbReceivedData.Append(Encoding.UTF8.GetString(abBuffer, 0, nBytesRead));
// decrease read timeout to nReadTimeoutMS second now that data is coming in
oNetworkStream.ReadTimeout = nReadTimeoutMS;
}
}
catch (IOException)
{
// read timed out, all data has been retrieved
nBytesRead = 0;
}
}
while (nBytesRead > 0);
//send the data to the callback and get the response back
byte[] abResponse = oClientHandlerDelegate(sbReceivedData.ToString(), oTCPClient);
if (abResponse != null)
{
oNetworkStream.Write(abResponse, 0, abResponse.Length);
oNetworkStream.Flush();
}
}
}
catch (Exception e)
{
Logger.Write(new TCPLogEntry("Caught Exception " + e.StackTrace));
}
finally
{
// stop talking to client
if (oTCPClient != null)
{
oTCPClient.Close();
}
}
}
编辑:我在两台完全独立的机器(我的 XP 开发机器和 colo 中的 2003 盒子)上得到大致相同的数字。我已经在相关部分的代码中添加了一些时间(使用 System.Diagnostic.StopWatch)并将其转储到日志中:
2009 年 7 月 6 日下午 3:44:50:调试:虽然 DataAvailable 花了 0 毫秒 2009 年 7 月 6 日下午 3:44:50:调试:读取耗时 531 毫秒 2009 年 7 月 6 日下午 3:44:50:调试:ProcessConnection 花了 577 毫秒