【问题标题】:TIdTCPServer not reading data from socket sometimesTIdTCPServer 有时不从套接字读取数据
【发布时间】:2009-10-02 00:05:05
【问题描述】:

我在 TIdTCPServer(安装附带的 Delphi 2009 和 Indy 10)的 OnExecute 中有以下代码,这与本网站上的其他示例非常相似;

   Socket := AContext.Connection.Socket;
    if Socket.CheckForDataOnSource(10) then
    begin
      if not Socket.InputBufferIsEmpty then
      begin
        Socket.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);

        SetLength(Buffer, Length(RawBytes));
        Move(RawBytes[0], Buffer[1], Length(RawBytes));

        // Do stuff with data here...
      end;
    end;
    AContext.Connection.CheckForGracefulDisconnect;

有时它不会读取数据,因为 CheckForDataOnSource(10) 返回 False。但是,如果我在该行停止调试器,我可以看到我在 InputBuffer 的字节中发送的数据。是否有任何其他设置我应该做的事情或其他方法来强制它一直工作。这段代码运行了很多次,但在 CheckForDataOnSource(10) 上总是失败。

另外作为旁注,我注意到在 Indy 的代码中,有些人使用 AContext.Connection.IOHandler 而不是 AContext.Connection.Socket 并执行与上面代码相​​同的操作,“什么是”正确”的使用。

谢谢

布鲁斯

【问题讨论】:

  • 仅供参考,D2009 附带的 Indy 10 版本中存在错误,这些错误已在 Indy SVN 的后续快照中修复。您应该考虑升级您的 Indy 安装。

标签: delphi delphi-2009 indy


【解决方案1】:

代码应该更像这样:

var
  IO: TIdIOHandler.
  Buffer: RawByteString;
begin
  IO := AContext.Connection.IOHandler;

  if IO.InputBufferIsEmpty then
  begin
    IO.CheckForDataOnSource(10);
    if IO.InputBufferIsEmpty then Exit;
  end;

  IO.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);     
  // or: IO.ReadBytes(RawBytes, -1, False);

  SetLength(Buffer, Length(RawBytes));
  BytesToRaw(RawBytes, Buffer[1], Length(RawBytes));
  // Do stuff with Buffer here...
end;

【讨论】:

    【解决方案2】:

    看起来你的代码应该是这样的;

    Socket := AContext.Connection.Socket;
    Socket.CheckForDataOnSource(10);
    if not Socket.InputBufferIsEmpty then
    begin
      Socket.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);
    
      SetLength(Buffer, Length(RawBytes));
      Move(RawBytes[0], Buffer[1], Length(RawBytes));
    
      // Do stuff with data here...
    end;
    AContext.Connection.CheckForGracefulDisconnect;
    

    你抓取什么 IOHandler 并不重要,所以通用的似乎是可行的。

    很抱歉回答我自己的问题,但这对某人来说可能很重要......也许吧。

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 2014-06-07
      • 2012-06-17
      • 2012-06-26
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多