Delphi XE IdTCPClient和IdTCPServer 发送和接收文件

Delphi XE IdTCPClient和IdTCPServer 发送和接收文件

1、IdTCPClient1 发送示例

var
  iFileHandle: integer;
  iFileLen, cnt: integer;
  buf: TIdBytes;
  lfilename: string;
  ln: Cardinal;
begin
  if dlgOpen1.Execute then
  begin
    lfilename := dlgOpen1.FileName;
  end;
  if lfilename <> '' then
  begin
    SetLength(buf, 4096);
    iFileHandle := FileOpen(lfilename, fmOpenRead);
    iFileLen := FileSeek(iFileHandle, 0, 2);
    FileSeek(iFileHandle, 0, 0);
    ProgressBar1.Max := iFileLen;
    ProgressBar1.Position := 0;
    IdTCPClient1.IOHandler.WriteLn(ExtractFileName(lfilename) + '|' + IntToStr(iFileLen));
    while true do
    begin
      Application.ProcessMessages;
      cnt := FileRead(iFileHandle, buf[0], 4096);
      ln := GetLastError;
      IdTCPClient1.IOHandler.Write(buf, cnt);
      ProgressBar1.Position := ProgressBar1.Position + cnt;
      mmo1.Lines.Add('正在传送文件...' + DateTimeToStr(Now));
      if cnt < 4096 then
        break;
    end;
    FileClose(iFileHandle);
    mmo1.Lines.Add('文件传送完成!' + DateTimeToStr(Now));

    SetLength(buf, 0);
  end;
end;

  

2、IdTCPServer 接收 示例

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
  rbyte: TIdBytes;
  sFile: TFileStream;
  cmd, FileSize: integer;
  str, FileName: string;
begin
  if not TIdYarnOfThread(AContext.Yarn).Thread.Terminated and AContext.Connection.Connected then  //注意这里
  begin
    with AContext.Connection do
    begin
      try
        str := IOHandler.ReadLn;   //接收文件大小及文件名
        cmd := pos('|', str); //查找分隔符
        FileName := copy(str, 1, cmd - 1); //提取文件名
        FileSize := StrToInt(copy(str, cmd + 1, Length(str) - cmd + 1)); //提取文件大小
 
        sFile := TFileStream.Create(ExtractFilePath(ParamStr(0)) + '\' + FileName, fmCreate);
        while FileSize > 4096 do
        begin
          Application.ProcessMessages;
          IOHandler.ReadBytes(rbyte, 4096,False); // 读取文件流  这里要注意 必须 false
          sFile.Write(rbyte[0], 4096);      //写入文件流
          mmo1.Lines.Add('正在接收文件中...' + DateTimeToStr(Now));
          inc(FileSize, -4096);
        end;
        IOHandler.readbytes(rbyte, FileSize);
        sFile.Write(rbyte[0], FileSize);
        sFile.Free;
        mmo1.Lines.Add('文件接收完成!' + DateTimeToStr(Now));
      finally
 
      end;
    end;
  end;
 
end;

  

 

 

 

创建时间:2020.06.23  更新时间:

 

你可能感兴趣的:(Delphi XE IdTCPClient和IdTCPServer 发送和接收文件)