0

给定以下代码,这是TIdTCPClient我的程序运行时 与我有任何关系的第一个代码

try
  if not TCPclient.Connected then
  begin
     TraceInfo(TCPclient.Host + ' Server not connected - reconnect');
     TCPclient.Connect();

     TCPclient.GetResponse(200);
     ConnectedToServer();
     TraceInfo(TCPclient.Host + ' Connect OK');
  end;

except   // when trying to connect to server
    on EIdAlreadyConnected : Exception do
    begin
       TraceWarning(TCPclient.Host + ' Attempt to Connect when already connected');
    end
    else    // Failed to connect for any other reason
    begin
       TraceError(TCPclient.Host + ' Connect FAILED !!!!');
       Exit; 
    end;
end;

// we either connected or noticed that we were already connected
try
  resultCode := TCPclient.SendCmd(theMessage);
  if resultCode = 200 then
  begin
     TraceInfo(TCPclient.Host + ' Sent OK');
     Result := TCPclient.LastCmdResult.Text.Text;
     DisconnectFromServer(TCPclient);
     Exit;
  end
  else
  begin
     TraceWarning(TCPclient.Host + ' Send rejected by server (result code = ' + IntToStr(resultCode) + ') !!!!');
      DisconnectFromServer(TCPclient);
      Exit;
  end;

except
  on E : Exception do       // EIdNotConnected
  begin
     Result := '';
     TraceError(TCPclient.Host + ' Send FAILED (exception "' + E.ClassName + '")');
  end;

结尾;

我不明白为什么跟踪日志说

00:00:00 [10.21.18.211 Server not connected - reconnect]    12:21:38 PM
00:00:01 [10.21.18.211 Attempt to Connect when already connected]   12:21:40 PM
00:00:01 [10.21.18.211 FAILED to connect to server] 12:21:40 PM
00:00:01 [10.21.18.211 Send FAILED (exception "EIdNotConnected")]   12:21:40 PM

任何人都可以看到我的代码明显有问题吗?或者我可以提供更多信息来帮助您帮助我吗?

提前致谢


更新,澄清:

我们怎么能有

如果不是 TCPclient.Connected 然后开始 TraceInfo(TCPclient.Host + 'Server not connected - reconnect');

进而

 TraceError(TCPclient.Host + ' Send FAILED (exception "' + E.ClassName + '")');
4

2 回答 2

3

在内部,Connected()执行读取操作以确定套接字状态。如果IOHandler.InputBuffer不为空,即使套接字物理断开,Connected()也会返回 True。 Connect()内部调用Connected()并在返回 True 时引发EIdAlreadyConnected异常Connected(),因此您的第一次调用可能Connected()正在接收导致第二次调用Connected()返回 True 的新数据。

于 2012-08-15T18:44:44.173 回答
2

您尚未提供 ConnectedToServer() 过程/方法的列表。如果此过程尝试连接 TCPclient 对象,那么这将解释您的结果。

于 2012-08-15T06:58:05.643 回答