不熟,最好用Delphi里面的SendStream;
function TCustomWinSocket.SendStreamPiece: Boolean;
var
Buffer: array[0..4095] of Byte;
StartPos: Integer;
AmountInBuf: Integer;
AmountSent: Integer;
ErrorCode: Integer;
procedure DropStream;
begin
if FDropAfterSend then Disconnect(FSocket);
FDropAfterSend := False;
FSendStream.Free;
FSendStream := nil;
end;
begin
Lock;
try
Result := False;
if FSendStream <> nil then
begin
if (FSocket = INVALID_SOCKET) or (not FConnected) then exit;
while True do
begin
StartPos := FSendStream.Position;
AmountInBuf := FSendStream.Read(Buffer, SizeOf(Buffer));
if AmountInBuf > 0 then
begin
AmountSent := send(FSocket, Buffer, AmountInBuf, 0);
if AmountSent = SOCKET_ERROR then
begin
ErrorCode := WSAGetLastError;
if ErrorCode <> WSAEWOULDBLOCK then
begin
Error(Self, eeSend, ErrorCode);
Disconnect(FSocket);
DropStream;
if FAsyncStyles <> [] then Abort;
Break;
end else
begin
FSendStream.Position := StartPos;
Break;
end;
end else if AmountInBuf > AmountSent then
FSendStream.Position := StartPos + AmountSent
else if FSendStream.Position = FSendStream.Size then
begin
DropStream;
Break;
end;
end else
begin
DropStream;
Break;
end;
end;
Result := True;
end;
finally
Unlock;
end;
end;
===========
自己写也没有什么不好理解的。
//没有经过测试,
procedure TForm1.Button1Click(Sender: TObject);
var
ReadNum: Integer;
FileStream: TFileStream;
Buf: array[0..4095] of Char;
begin
if not dlgOpen1.Execute then Exit;
FileStream := TFileStream.Create(FileName, fmOpenReadWrite);
try
repeat
try //流在读取到数据后自动将position移到当前+读取到的位置
//清空缓冲
FillChar(Buf, SizeOf(Buf), #0);
//读取文件数据到缓冲
ReadNum := FileStream.Read(Buf, SizeOf(Buf));
//如读到的长度大于0就发送出去。
if ReadNum > 0 then
ServerSocket1.Socket.SendBuf(Buf, ReadNum);
except on E: Exception do
begin
ShowMessage(E.Message);
Break;
end;
end;
until FileStream.Position = FileStream.Size;
finally
//释放stream
FileStream.Free;
end;
end;