服务端用TIdTcpServer, 加了IdThreadMgrDefault控件和IdAntiFreeze控件.在win2003的服务器上运行经常CPU接近100%!!
很郁闷,请大师们指点小弟
procedure TfrmMain.ServerTCPExecute(AThread: TIdPeerThread);
var
  cmd: byte;
begin
  try
    if (not AThread.Terminated) and (AThread.Connection.Connected) then
    begin
      with AThread do
      begin
        Connection.ReadBuffer(cmd,1);        if cmd = 1 then   //发送最新公告
        begin
          Connection.WriteBuffer(PubNote, SizeOf(PubNote));
        end
        else if cmd = 2 then  //设置最新公告 这种情况很少,一般不会执行
        begin
          Connection.ReadBuffer(tmpPubNote, SizeOf(tmpPubNote));
          Synchronize(SetNewPubNote);
          cmd := 3;
          Connection.WriteBuffer(cmd,1);  //设置成功
        end;
      end;
    end;
    Sleep(50);
  except
   // AThread.Connection.DisconnectSocket;
   { on e: Exception do
      ShowMessage(e.Message); }
  end;
end;procedure TfrmMain.ServerTCPException(AThread: TIdPeerThread;
  AException: Exception);
begin
  try
    AThread.Connection.DisconnectSocket;
  except
  end;
end;

解决方案 »

  1.   

    最大连接允许3000个  非堵塞模式的.
    连接达到30多个的时候就会CPU100%  等待队列为3. 客户端会频繁的连接和断开,难道是服务端处于等待的连接数太多时就会导致CPU100%吗?
      

  2.   

    cmd多数为1还是2?Connection.WriteBuffer(PubNote, SizeOf(PubNote)); 
    Connection.ReadBuffer(tmpPubNote, SizeOf(tmpPubNote)); 
    这2个Note的空间是多少?
      

  3.   

    Don't use Synchronize.
    Sleep(1)
      

  4.   

    基本上都是last_ack
    TPubNote = record
      note     :string[255];
      pubtime  :string[30];
    end;
      

  5.   

    Sleep(50); 放到最上面去.9的支持几百个没什么问题的.CPU也不会占用太高
      

  6.   

    不需要sleep,为何需要sleep?sleep后只会使你来不及处理客户端的请求。本质上是客户端向服务器的请求太频繁太多。
      

  7.   

    去掉SLEEP
    或者sleep(0);
      

  8.   

      楼上二位试过没有? 看了 TcpServer.OnExecute的代码了吗?
      

  9.   

    另一个地方是,如果已经很忙了,不要在这里使用Synchronize,因为同步到主线程时,如果主线程恰好很忙,这个peerthread就会等待主线程,也学可以用postmessage来异步处理。与不要使用sleep一样,应该尽早结束peerthread,让它能服务下一个调用,而不是sleep(50)要空等50毫秒才能进入pool。
    但是这些与你CPU占100%没关系,因为你并没有执行额外的多余的事情,视客户端的状况,你的CPU就是应该这样忙。