我有一个用 Delphi 11 编写的应用程序。我使用 TIdHttp 客户端接收来自摄像机的实时流。数据在 OnWork 事件中接收。
我的代码看起来像这样
procedure TStreamingThread.IdHttpLiveStreamWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
MemoryStream: TMemoryStream;
BytesToRead: NativeInt;
begin
MemoryStream := TMemoryStream.Create;
try
BytesToRead := IdHttpLiveStream.Response.ContentStream.Position - LastPosition;
//read from where we got up to last time to the end of the stream
IdHttpLiveStream.Response.ContentStream.Position := LastPosition;
MemoryStream.CopyFrom(IdHttpLiveStream.Response.ContentStream, BytesToRead);
//extract the jpg data from the stream and use it update the screen
//update LastPosition so that we are ready for the next time
LastPosition := LastPosition + BytesToRead;
finally
MemoryStream.Free;
end;
我使用提取的 jpg 数据来更新 TPicture,一切正常。
我的问题是关于 ContentStream 的。它的大小不会不断增加并最终导致内存不足错误吗?我应该重置它吗?如果是的话怎么重置?
是的,
ContentStream
将继续被写入,因此如果您使用像TMemoryStream
这样的目标流,那么它将继续增长。每次你消费它时,你都必须Clear()
它。否则,您可以考虑使用 TIdEventStream
代替其 OnWrite
事件。
话虽如此,
TIdHTTP
并不是真正为处理流媒体而设计的。但是,根据响应的实际格式,您可能有一些选择。例如,如果使用 HTTP 块发送媒体数据,您可以使用 TIdHTTP.OnChunkReceived
事件。或者,如果媒体类型是 'multipart/...'
,例如 'multipart/x-mixed-replace'
(或者数据是分块的),则可以使用 hoNoReadMultipartMIME
(或 hoNoReadChunked
)选项标志告诉 TIdHTTP
不要读取响应正文完全可以,让您直接使用 IOHandler
自行阅读正文。