Adhy
Adhy

Reputation: 92

How to write and read Stream using indy 10.5.5 c++

Hi I have try to read Stream from the server with this code

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, wchar_t &Key)
{
   //TMemoryStream *TMS = new TMemoryStream;
   TStringStream *TSS = new TStringStream;
   AnsiString A,B;
   TStream *TS;
   INT64 Len;
   try
   {
       if (Key == VK_RETURN)
       {
          Beep(0,0);
          if(Edit1->Text == "mystream")
           {
               TCPClient1->IOHandler->WriteLn("mystream");
               Len = StrToInt(TCPClient1->IOHandler->ReadLn());
               TCPClient1->IOHandler->ReadStream(TS,Len,false);
               TSS->CopyFrom(TS,0);
               RichEdit1->Lines->Text = TSS->DataString;
               Edit1->Clear();
           }
       else
           {
              TCPClient1->IOHandler->WriteLn(Edit1->Text);
              A = TCPClient1->IOHandler->ReadLn();
              RichEdit1->Lines->Add(A);
              Edit1->Clear();
           }
       }
   }
   __finally
   {
       TSS->Free();
   }

}

and every times client try to read stream from the server, compiler says.

First chance exception at $75D89617. Exception class EAccessViolation with message 'Access violation at address 500682B3 in module 'rtl140.bpl'. Read of address 00000018'. Process Project1.exe (6056)

How to handle this?

Upvotes: 0

Views: 1767

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596998

You are not instantiating your TStream object before calling ReadStream(). Your TS variable is completely uninitialized. ReadStream() does not create the TStream object for you, only writes to it, so you have to create the TStream yourself beforehand.

Given the code you have shown, you can replace the TStream completely by using the ReadString() method instead:

void __fastcall TForm1::Edit1KeyPress(TObject *Sender, wchar_t &Key) 
{ 
    if (Key == VK_RETURN) 
    { 
        Beep(0,0); 
        if (Edit1->Text == "mystream") 
        { 
            TCPClient1->IOHandler->WriteLn("mystream"); 
            int Len = StrToInt(TCPClient1->IOHandler->ReadLn()); 
            RichEdit1->Lines->Text = TCPClient1->IOHandler->ReadString(Len); 
        } 
        else 
        { 
            TCPClient1->IOHandler->WriteLn(Edit1->Text); 
            String A = TCPClient1->IOHandler->ReadLn(); 
            RichEdit1->Lines->Add(A); 
        } 
        Edit1->Clear(); 
    } 
} 

Upvotes: 3

Related Questions