TIdTCPServer有时不会从套接字读取数据

时间:2009-10-02 00:05:06

标签: delphi delphi-2009 indy

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

   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并做了与上面代码相​​同的事情,那是什么“对“一个人使用。

谢谢

布鲁斯

2 个答案:

答案 0 :(得分:5)

代码应该更像这样:

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;

答案 1 :(得分:0)

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

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并不重要,所以通用的就好了。

对于回答我自己的问题感到很抱歉,但对于某些人来说可能很有意思......也许。

相关问题