Delphi XE IdTCPClient和IdTCPServer 发送和接收文件
Delphi XE IdTCPClient和IdTCPServer 发送和接收文件
1、IdTCPClient1 发送示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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 接收 示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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 更新时间:
博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你有所帮助,谢谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报