我的“未连接”TCP客户端已连接?

时间:2012-08-15 04:46:05

标签: delphi indy10

给出以下代码,这是我的程序运行时第一个与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 +'服务器未连接 - 重新连接');

然后

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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