DataSnap Stream 传递大数据

DataSnap可以直接传递和返回TStream类型的参数,这点是很方便的。但是很多人发现好像大小稍微大点就工作不正常了。

DataSnap默认的缓存大小是32k 所以如果流的大小超过这个大小就会被自动分成多个包,这就是传递大量数据的基础,如果一次性发送就可能受到内存的限制。

当传递大量数据时获取到的大小是-1,所以如果还是按照一般的方法来读取流的数据就会有问题了。

由于流的数据是原始数据包发送,所以在不对数据包压缩加密的情况下,传递速度是和其它方式没有多大区别的。

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// FS是一个文件流
function TMyDSServer.PutFile(Stream: TStream): Boolean;
const
  BufSize = $F000;
var
  Buffer: TBytes;
  ReadCount: Integer;
begin
  if Stream.Size = -1 then  // 大小未知则一直读取到没有数据为止
  begin
    SetLength(Buffer, BufSize);
    repeat
      ReadCount := Stream.Read(Buffer[0], BufSize);
      if ReadCount > 0 then
        FS.WriteBuffer(Buffer[0], ReadCount);
      if ReadCount < BufSize then
        break;
    until ReadCount < BufSize;
  end
  else // 大小已知则直接复制数据
    FS.CopyFrom(Stream, 0);
  Result := True;
end;

function TdmCommonFun.DownLoadFile(const FileName: string): Boolean;
var
a: TServerMethods1Client;
ini: TIniFile;
Stream, ms: TStream;
Buffer: TBytes;
ReadCount: Integer;
const
BufSize = $F000;
begin
Result := False;
if (not TryConnectAPPServer) or (FileName = '') then
Exit;
a := TServerMethods1Client.Create(SQLConnection1.DBXConnection);
ms := TMemoryStream.Create;
try
Stream := a.DownLoadFile(FileName);
if Stream.Size = -1 then
begin
SetLength(Buffer, BufSize);
repeat
ReadCount := Stream.Read(Buffer[0], BufSize);
if ReadCount > 0 then
ms.WriteBuffer(Buffer[0], ReadCount);
if ReadCount < BufSize then
break;
until ReadCount < BufSize;
end
else
begin
ms.CopyFrom(Stream, 0);
end;
// delete bak files
if FileExists(ExtractFilePath(Application.ExeName) + FileName + 'bak') then
DeleteFile(PWideChar(ExtractFilePath(Application.ExeName) + FileName
+ 'bak'));
// 现有文件改名
if FileExists(ExtractFilePath(Application.ExeName) + FileName) then
begin
RenameFile(ExtractFilePath(Application.ExeName) + FileName,
ExtractFilePath(Application.ExeName) + FileName + 'bak');
end;
// 下载最新文件
TMemoryStream(ms).SaveToFile(ExtractFilePath(Application.ExeName) +
FileName);
// 更新本机版本号
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'client.ini');
try
ini.WriteInteger(FileName, 'ver', GetVer(FileName));
finally
ini.Free;
end;
finally
a.Free;
ms.Free;
end;
Result := True;
end;

原文地址:https://www.cnblogs.com/hnxxcxg/p/2785088.html