簡體   English   中英

Delphi 2009,Indy 10,TIdTCPServer.OnExecute,如何獲取InputBuffer中的所有字節

[英]Delphi 2009, Indy 10, TIdTCPServer.OnExecute, how to grab all the bytes in the InputBuffer

我正在搞亂Delphi 2009提供的Indy 10,並且在OnExecute觸發時無法從IOHandler獲取所有數據......

procedure TFormMain.IdTCPServerExecute(AContext: TIdContext);
var
  RxBufStr: UTF8String;
  RxBufSize: Integer;
begin

  if AContext.Connection.IOHandler.Readable then
  begin
    RxBufSize := AContext.Connection.IOHandler.InputBuffer.Size;
    if RxBufSize > 0 then
    begin
      SetLength(RxBufStr, RxBufSize);
      AContext.Connection.IOHandler.ReadBytes(TBytes(RxBufStr), RxBufSize, False);
    end;
  end;

end;

AContext.Connection.IOHandler.InputBuffer.Size似乎不可靠並經常返回0,但是在下一次運行時,OnExecute它將獲取正確的字節數,但為時已晚。

基本上我希望能夠只獲取所有數據,將其填充到UTF8String( 不是 Unicode字符串),然后解析一個特殊的標記。 所以我沒有標題,消息長度可變。 似乎Indy 10 IOHandlers沒有為此設置,或者我只是錯誤地使用它。

做一些像傳遞一定大小的緩沖區,盡可能多地填充它並返回實際填充的字節數然后繼續運行(如果還有更多)會很好。

除了TIdSchedulerOfFiber的狀態之外,這看起來非常有趣,它有用嗎? 有人用嗎? 我注意到它不在Delphi 2009的標准安裝中。

更新:我發現Msg:= AContext.Connection.IOHandler.ReadLn(#0,enUTF8); 哪個有效,但我仍然想知道上述問題的答案,是因為它是基於阻止IO嗎? 這使得TIdSchedulerOfFiber更加熱衷於此。

你不應該像那樣使用Readable()。 請嘗試以下方法:

procedure TFormMain.IdTCPServerExecute(AContext: TIdContext);
var
  RxBuf: TIdBytes;
begin
  RxBuf := nil;
  with AContext.Connection.IOHandler do
  begin
    CheckForDataOnSource(10);
    if not InputBufferIsEmpty then
    begin
      InputBuffer.ExtractToBytes(RxBuf);
      // process RxBuf as needed...
    end;
  end;
end;

或者:

procedure TFormMain.IdTCPServerExecute(AContext: TIdContext);
var
  RxBufStr: String; // not UTF8String
begin
  with AContext.Connection.IOHandler do
  begin
    CheckForDataOnSource(10);
    if not InputBufferIsEmpty then
    begin
      RxBufStr := InputBuffer.Extract(-1, enUtf8);

      // Alternatively to above, you can set the
      // InputBuffer.Encoding property to enUtf8
      // beforehand, and then call TIdBuffer.Extract()
      // without any parameters.
      //
      // Or, set the IOHandler.DefStringEncoding
      // property to enUtf8 beforehand, and then
      // call TIdIOHandler.InputBufferAsString()

      // process RxBufStr as needed...
    end;
  end;
end;

至於TIdSchedulerOfFiber - 此時SuperCore包實際上已經死了。 它在很長一段時間內都沒有開始工作,並且不與最新的Indy 10架構保持同步。 我們可能會在以后嘗試復活它,但它不在我們不久的將來的計划中。

procedure TFormMain.IdTCPServerExecute(AContext: TIdContext); 
var
  RxBufStr: UTF8String;
  RxBufSize: Integer;
begin    
  if AContext.Connection.IOHandler.Readable then
  begin     
    AContext.Connection.IOHandler.ReadBytes(TBytes(RxBufStr),-1, False);
  end;
end; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM