我使用此代碼向客戶端發送文件。Indy發送文件並關閉打開的句柄
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;
這就像一個魅力,但如果客戶端斷開連接,而該文件被髮送,印地終止立即執行線程,這樣的文件句柄仍然是開放的!客戶端斷開連接後有沒有辦法關閉文件句柄?
謝謝你的幫助。
您嘗試使用'try..finally..end '? – RRUZ 2012-08-11 00:43:42