Вопрос по multithreading – Глобал, потокобезопасен, менеджер куки с Indy

2

Мое приложение Delphi 2010 загружает данные, используя многопоточность, загруженные данные помещаются в PHP / веб-приложение, которое требует входа в систему, поэтому мне нужно использовать менеджер общих / глобальных файлов cookie (я используюIndy10 Revision 4743), так как TIdCookieManager не является потокобезопасным :(

Кроме того, на стороне сервера, идентификатор сессии автоматически генерируется каждые 5 минут, поэтому яmust сохранить как глобальный & amp; локальные менеджеры печенья в синхронизации.

Мой код выглядит так:

TUploadThread = class(TThread)
// ...

var
   GlobalCookieManager : TIdCookieManager;

procedure TUploadThread.Upload(FileName : String);
var
   IdHTTP           : TIdHTTP;
   TheSSL           : TIdSSLIOHandlerSocketOpenSSL;
   TheCompressor    : TIdCompressorZLib;
   TheCookieManager : TIdCookieManager;
   AStream          : TIdMultipartFormDataStream;
begin
     ACookieManager := TIdCookieManager.Create(IdHTTP);

     // Automatically sync cookies between local & global Cookie managers
     @TheCookieManager.OnNewCookie := pPointer(Cardinal(pPointer( procedure(ASender : TObject; ACookie : TIdCookie; var VAccept : Boolean)
     begin
          OmniLock.Acquire;
          try
             GlobalCookieManager.CookieCollection.AddCookie(ACookie, TIdHTTP(TIdCookieManager(ASender).Owner).URL{IdHTTP.URL});
          finally
                  OmniLock.Release;
          end;    // try/finally

          VAccept := True;
     end )^ ) + $0C)^;
     // ======================================== //


     IdHTTP         := TIdHTTP.Create(nil);
     with IdHTTP do
     begin
          HTTPOptions     := [hoForceEncodeParams, hoNoParseMetaHTTPEquiv];
          AllowCookies    := True;
          HandleRedirects := True;
          ProtocolVersion := pv1_1;

          IOHandler       := TheSSL;
          Compressor      := TheCompressor;
          CookieManager   := TheCookieManager;
     end;    // with

     OmniLock.Acquire;
     try
        // Load login info/cookies
        TheCookieManager.CookieCollection.AddCookies(GlobalCookieManager.CookieCollection);
     finally
            OmniLock.Release;
     end;    // try/finally

     AStream         := TIdMultipartFormDataStream.Create;

     with Stream.AddFile('file_name', FileName, 'application/octet-stream') do
     begin
          HeaderCharset  := 'utf-8';
          HeaderEncoding := '8';
     end;    // with

     IdHTTP.Post('https://www.domain.com/post.php', AStream);
     AStream.Free;
end;

Но это не работает! Я получаю это исключение при вызове AddCookies ()

Project MyEXE.exe raised exception class EAccessViolation with message 'Access violation at address 00000000. Read of address 00000000'.

Я также пытался использовать assign (), т.е.

 TheCookieManager.CookieCollection.Assign(GlobalCookieManager.CookieCollection);

Но я все еще получаю то же исключение, обычно здесь:

 TIdCookieManager.GenerateClientCookies()

Кто-нибудь знает, как это исправить?

Error: User Rate Limit Exceeded TheDude
Error: User Rate Limit ExceededFRWLock.BeginWrite;Error: User Rate Limit ExceededTIdCookies.LockCookieList(AAccessType: TIdCookieAccess): TIdCookieList; TheDude
Error: User Rate Limit ExceededOnNewCookieError: User Rate Limit ExceededTIdCookieManagerError: User Rate Limit ExceededSelfError: User Rate Limit Exceeded Remy Lebeau
Error: User Rate Limit Exceededend )^ ) + $0C)^;Error: User Rate Limit Exceeded Mason Wheeler
Error: User Rate Limit ExceededGlobalCookieManagerError: User Rate Limit ExceededinitializationError: User Rate Limit ExceededfinalizationError: User Rate Limit Exceeded Remy Lebeau

Ваш Ответ

3   ответа
2

Thank you guys, I converted to a normal method, but I'm still getting exceptions in AddCookies(), last one happened in the line that reads FRWLock.BeginWrite; in this procedure TIdCookies.LockCookieList(AAccessType: TIdCookieAccess): TIdCookieList;

Read of address 00000000nil.

SelfFRWLock являетсяnil

Error: User Rate Limit ExceededGlobalCookieManagerError: User Rate Limit Exceeded
3

 // Automatically sync cookies between local & global Cookie managers
 @TheCookieManager.OnNewCookie := pPointer(Cardinal(pPointer( procedure(ASender : TObject; ACookie : TIdCookie; var VAccept : Boolean)
 begin
      OmniLock.Acquire;
      try
         GlobalCookieManager.CookieCollection.AddCookie(ACookie, TIdHTTP(TIdCookieManager(ASender).Owner).URL{IdHTTP.URL});
      finally
              OmniLock.Release;
      end;    // try/finally

      VAccept := True;
 end )^ ) + $0C)^;

$0C

5

OnNewCookie

procedure TUploadThread.NewCookie(ASender: TObject; ACookie : TIdCookie; var VAccept : Boolean);
var
  LCookie: TIdCookie;
begin
  LCookie := TIdCookieClass(ACookie.ClassType).Create;
  LCookie.Assign(ACookie);
  OmniLock.Acquire; 
  try 
    GlobalCookieManager.CookieCollection.AddCookie(LCookie, TIdHTTP(TIdCookieManager(ASender).Owner).URL); 
  finally 
    OmniLock.Release; 
  end;
  VAccept := True;
end;

procedure TUploadThread.NewCookie(ASender: TObject; ACookie : TIdCookie; var VAccept : Boolean);
begin
  OmniLock.Acquire; 
  try 
    GlobalCookieManager.CookieCollection.AddServerCookie(ACookie.ServerCookie, TIdHTTP(TIdCookieManager(ASender).Owner).URL); 
  finally 
    OmniLock.Release; 
  end;
  VAccept := True;
end;

procedure TUploadThread.Upload(FileName : String); 
var 
  IdHTTP           : TIdHTTP; 
  TheSSL           : TIdSSLIOHandlerSocketOpenSSL; 
  TheCompressor    : TIdCompressorZLib; 
  TheCookieManager : TIdCookieManager; 
  TheStream        : TIdMultipartFormDataStream; 
begin 
  IdHTTP := TIdHTTP.Create(nil); 
  try
    ...
    TheCookieManager := TIdCookieManager.Create(IdHTTP); 
    TheCookieManager.OnNewCookie := NewCookie;

    with IdHTTP do 
    begin 
      HTTPOptions     := [hoForceEncodeParams, hoNoParseMetaHTTPEquiv]; 
      AllowCookies    := True; 
      HandleRedirects := True; 
      ProtocolVersion := pv1_1; 

      IOHandler       := TheSSL; 
      Compressor      := TheCompressor; 
      CookieManager   := TheCookieManager; 
    end;    // with 

    OmniLock.Acquire; 
    try 
      // Load login info/cookies 
      TheCookieManager.CookieCollection.AddCookies(GlobalCookieManager.CookieCollection); 
    finally 
      OmniLock.Release; 
    end;

    TheStream := TIdMultipartFormDataStream.Create; 
    try
      with TheStream.AddFile('file_name', FileName, 'application/octet-stream') do 
      begin 
        HeaderCharset  := 'utf-8'; 
        HeaderEncoding := '8'; 
      end;

      IdHTTP.Post('https://www.domain.com/post.php', TheStream); 
    finally
      TheStream.Free; 
    end;
  finally
    IdHTTP.Free;
  end;
end; 
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededAddCookie()Error: User Rate Limit ExceededTIdCookieManagerError: User Rate Limit ExceededOnNewCookieError: User Rate Limit ExceededAddCookie()Error: User Rate Limit ExceededACookieError: User Rate Limit ExceededACookieError: User Rate Limit ExceededAddServerCookie(ACookie.ServerCookie)Error: User Rate Limit ExceededAddCookie().
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededmy comment here TheDude

Похожие вопросы