这是我的一个非常简单的 TCP 服务器的代码(基本上是示例异步服务器套接字示例 - http://goo.gl/Ix5C - 稍作修改):
public static void InitiateListener()
{
try
{
allDone = new ManualResetEvent(false);
configFile = new XmlConfig();
StartListening();
}
catch (Exception exc)
{
LogsWriter f = new LogsWriter(configFile.ErrorLogsPath);
f.WriteToFile(exc.Message);
f.CloseFile();
}
}
private static void StartListening()
{
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, configFile.Port);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception exc)
{
throw exc;
}
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set(); // Signal the main thread to continue.
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
string hexData = string.Empty;
// Retrieve the state object and the handler socket from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
try
{
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
hexData = BitConverter.ToString(state.buffer);
if (hexData.Contains("FA-F8")) //heartbeat - echo the data back to the client.
{
byte[] byteData = state.buffer.Take(bytesRead).ToArray();
handler.Send(byteData);
}
else if (hexData.Contains("0D-0A")) //message
{
state.AsciiData = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
state.ParseMessage(configFile);
}
}
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
这一切都在 Windows 服务中。在完全可以接受的大约 2 天半的运行后,CPU 最高达到 100%。这种情况现在已经发生了 3 次 - Windows 服务始终可以正常工作并按预期运行,几乎没有使用 CPU 资源,但在第 3 天的某个时候达到 100% 并一直保持在那里,直到重新启动服务。
我得到了非常简单的 CSV 数据包,我快速解析并通过 Web 服务将其发送到数据库: state.ParseMessage(configFile); 即使 CPU 为 100%,数据库也可以非常可靠地填满。但我知道这可能是我需要调查的一个地方?
代码的哪些其他区域似乎可能导致问题?我是异步编程的新手,所以我不知道是否需要手动关闭线程。此外,这可能是另一个问题:
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
在 ReadCallback 本身中调用该行。我这样做是为了保持与客户端的连接并继续接收数据,但也许我应该关闭套接字并强制建立新连接?
你能提供一些建议吗?谢谢