我使用此代码将文件发送到客户端。
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
hFile : THandle;
FileBuff : array [0..1023] of byte;
dwRead : DWORD;
Recieved : String;
begin
Recieved := Athread.Connection.ReadLn;
if Recieved = 'FILE' then begin
Memo1.Lines.Add('Sending File...');
hFile := CreateFileW('FILE.bin',
GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if hFile = INVALID_HANDLE_VALUE then exit;
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
while true do begin
ReadFile(hFile, FileBuff[0], 1024, dwRead, nil);
if dwRead <= 0 then break;
Athread.Connection.WriteBuffer(FileBuff[0], dwRead);
end;
CloseHandle (hFile);
Athread.Connection.Disconnect;
end;
end;
这就像一个魅力,但如果客户端在文件发送时断开连接,Indy 会立即终止执行线程,因此文件句柄仍然打开!客户端断开连接后有没有办法关闭文件句柄?
感谢您的帮助。