![](/img/trans.png)
[英]C# TCP Client using high CPU when launched with Process.Start
[英]C# and TCP Client (Async) has very high CPU load & How to detect disconnected clients?
如果有多個客戶端連接,則CPU負載為90+。 如果我啟動監聽器並且沒有連接,那么一切都很好。 如果我有一個或多個Connections,我的CPU負載會很高。
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Test.Socket
{
public class Server
{
List<Thread> WorkListenerThread;
TcpListener Listener;
public Server()
{
WorkListenerThread = new List<Thread>();
}
public void Start()
{
try
{
Listener = new TcpListener(IPAddress.Any, 12345);
Listener.Start();
StartTCPClientListener();
}
catch (Exception) { }
}
private void StartTCPClientListener()
{
Listener.BeginAcceptTcpClient(new AsyncCallback(HandleTCPClientConnection), null);
}
private void HandleTCPClientConnection(IAsyncResult ar)
{
// Problem 1: after the first connection i have a high cpu load
try
{
TcpClient client = Listener.EndAcceptTcpClient(ar);
Thread clientThread = new Thread(Communicator.CreateConnection);
clientThread.Start(client);
WorkListenerThread.Add(clientThread);
StartTCPClientListener(); // Next client
}
catch (Exception) { }
}
public void Stop()
{
foreach (Thread th in WorkListenerThread)
if (th.IsAlive)
th.Abort();
// Problem 2: Exception because the "HandleTCPClientConnection" get a wrong IAsyncResult
if (Listener != null)
Listener.Stop();
}
}
}
還有我的客戶班。
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using JsonExSerializer;
namespace Test.Socket
{
class Communicator
{
private TcpClient TcpClient = null;
private NetworkStream Stream = null;
private Communicator(TcpClient client)
{
TcpClient = client;
Stream = TcpClient.GetStream();
StartCommunication();
}
public static void CreateConnection(object c)
{
new Communicator(c as TcpClient);
}
private void StartCommunication()
{
string message; // The message
int bytesRead; // Message length
byte[] buffer = new byte[512]; // buffer
while (true)
{
message = String.Empty;
do
{
bytesRead = Stream.Read(buffer, 0, buffer.Length);
message += Encoding.Default.GetString(buffer, 0, bytesRead);
} while (!message.EndsWith("\r\n.\r\n"));
Send("OK", Stream);
}
}
protected void Send(string message, NetworkStream clientStream)
{
byte[] temp = Encoding.Default.GetBytes(message);
clientStream.Write(temp, 0, temp.Length);
clientStream.Flush();
}
}
}
我不知道怎么了-.-
還有誰知道我如何檢測客戶端是否斷開連接? 那也很好。
但是解決高CPU負載就足夠了。
我猜主要問題在這里:
while (true)
{
message = String.Empty;
do
{
bytesRead = Stream.Read(buffer, 0, buffer.Length);
message += Encoding.Default.GetString(buffer, 0, bytesRead);
} while (!message.EndsWith("\r\n.\r\n"));
Send("OK", Stream);
}
您應該檢查這個bytesRead
是否為非正數; 如果是,那是流的末尾,你應該終止:沒有更多的數據是以往任何時候都來了,但你是在一個緊湊的循環追加空字符串永遠。
然而! 更大的問題是方法:每個客戶端線程根本無法擴展,這不是人們提到“異步IO”時的意思。
我還要說,讓構造函數啟動長時間運行的操作(因此不會返回)是一件可怕的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.