嗨,我尝试使用此代码从服务器读取流

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();
   }

}


编译器说,并且每当客户端尝试从服务器读取流时,编译器都会说。

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)


如何处理呢?

最佳答案

您没有在调用TStream之前实例化ReadStream()对象。您的TS变量是完全未初始化的。 ReadStream()不会为您创建TStream对象,只会对其进行写入,因此您必须事先创建TStream

给定您显示的代码,您可以使用TStream方法完全替换ReadString()

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();
    }
}

10-07 18:53