Search code examples
delphiindy10

TStream not converted to TStrings


I've checked the size of the stream and it's the same size on both the server and the client, so I think there isn't any data loss there. Should I use a different procedure to load the string from the stream?

Client code:

StreamSize:= TCPClient.IOHandler.ReadInt64;  //<Size of TStream

TCPClient.IOHandler.ReadStream(TStream(NotificationStream), StreamSize);

NotificationStrings := ConvertStreamToStrings(NotificationStream);
Notifications := ConvertStringsToNotifications(NotificationStrings);

Synchronize(procedure begin PutNotifications(Notifications); end);
StreamSize:= 0;

Convert stream function:

function ConvertStreamToStrings(ntfStream : TStream) : TStringList;
begin
  Result := TStringList.Create;
  Result.LoadFromStream(ntfStream, TEncoding.Default);
end;

Solution

  • You need to create the TStringList object that ConvertStreamToStrings() returns. Add this:

    Result := TStringList.Create;
    

    before the call to LoadFromStream().

    Of course, you also need to Free() the returned TStringList when you don't need it anymore.

    Edit after comments

    Also, you need to reset the stream's Position to 0 before you can load it to the TStringList, so the conversion function would look like this:

    function ConvertStreamToStrings(ntfStream: TStream): TStringList;
    begin
      ntfStream.Position := 0;
      Result := TStringList.Create;
      Result.LoadFromStream(ntfStream, TEncoding.Default);
    end;