我有一个tcp服务器应用程序,它接受更多数量的tcp客户端,并从所有连接的客户端接收连续消息。
public void KeepListening()
{
while (IsRunning)
{
try
{
Thread.Sleep(20);
if (tcpListener.Pending())
{
//Get the socket obtained from the tcpListener
TcpClient _Client = tcpListener.AcceptTcpClient();
NetworkStream ns = _Client.GetStream();
Thread.Sleep(20);
if (Stop_Status == false)
{
if (_Client.Connected)
{
int DataBytes = _Client.Available;
byte[] data = new byte[DataBytes];
if (ns.DataAvailable == true)
{
ns.Read(data, 0, DataBytes);
string Key = ASCIIEncoding.ASCII.GetString(data);
string[] KeyCodes = Key.Split(',');
if (Key != "" && ((KeyCodes[0].StartsWith("i"))))
ProcessClient(_Client, KeyCodes[0], Key);
}
}
}
else
{
ns.Flush();
}
}
}
catch
{
}
}
}
void ProcessClient(TcpClient _Client, string Key,string Msg)
{
try
{
if (hashTable_Users.Count > 0)
{
if (hashTable_Users.Contains(Key))
{
hashTable_Users.Remove(Key);
}
}
hashTable_Users.Add(Key, _Client);
hashusers = hashTable_Users.Count;
this.MessageFromClient(Key, serverPortNo.ToString(), Msg);
//StreamWriter sw = new StreamWriter(_Client.GetStream());
//sw.WriteLine("1");
//sw.Flush();
object[] objarr = new object[5];
objarr[0] = _Client;
objarr[1] = Key;
Thread ReceiveFromClient = new Thread(new ParameterizedThreadStart(ReceiveFromClients));
ReceiveFromClient.Start(objarr);
}
catch
{
}
}
public void ReceiveFromClients(object obj)
{
object[] objarr = (object[])obj;
TcpClient _Client = (TcpClient)objarr[0];
NetworkStream ns = _Client.GetStream();
while (IsRunning)
{
if (Stop_Status == false)
{
if (_Client.Connected)
{
if (ns.DataAvailable)
{
try
{
int numBytesRead = _Client.Available;
byte[] data = new byte[numBytesRead];
ns.Read(data, 0, numBytesRead);
string MsgReceived = ASCIIEncoding.ASCII.GetString(data);
string clientKey = objarr[1].ToString();
this.MessageFromClient(clientKey, serverPortNo.ToString(), MsgReceived);
}
catch
{
}
}
}
else
{
break;
}
}
else
{
ns.Flush();
}
}
}
KeepListening()
用于接受发送请求的客户端。 ProcessClient()
和ReceiveFromClients()
用于接收来自客户的消息。
此应用程序使用100%cpu。
请建议我如何降低cpu利用率?
答案 0 :(得分:1)
通过查看您的代码,ReceiveFromClients消耗大部分CPU,因为while(IsRunning),并且只有数据可用时才会读取。
要解决此问题,请不要检查IsAvailabele,调用ReadMethod来阻塞线程,直到ReadTimeOut发生或者某些数据已被读取。根据收到的字节数,处理您的数据。
答案 1 :(得分:0)
请建议我如何降低cpu利用率?
这看起来不错:
while (IsRunning)
{
try
{
...
}
catch
{
}
}
如果你反复获得异常,你将永远不会知道它 - 并且只是保持循环。你还有另一个空的捕获块......你真的不应该抓住所有东西而只是继续前进,甚至没有记录。
同样在这里:
while (IsRunning)
{
if (Stop_Status == false)
{
...
}
else
{
ns.Flush();
}
}
如果IsRunning
为真,且Stop_Status
为假,那就是紧急循环,重复调用Flush
......