我用以下使用socket接收文件的代碼試了好多次,但水平實在有限,執行時總是出現錯誤,可否幫我修改一下?謝謝.
clent端的:
private
stream : TMemoryStream;
size,count : integer;
end;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientSocket1.Address := Edit1.Text;
ClientSocket1.Active := True;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
stream := TMemoryStream.Create;
stream.LoadFromFile(OpenDialog1.FileName);
size := stream.Size;
count := 0;
ClientSocket1.Socket.SendText(inttostr(size));
end;
procedure TForm1.ClientSocket1Read(Sender: TObject;
Socket: TCustomWinSocket);
var
rcvtxt : string;
buf : array [1..2048] of char;
left : integer;
begin
rcvtxt := Socket.ReceiveText;
left := size - count;
if AnsiPos('go~',rcvtxt)=1 then
begin
if sizeof(buf)<left then
begin
stream.Read(buf,sizeof(buf));
Socket.SendBuf(buf,sizeof(buf));
count := count + sizeof(buf);
end
else
begin
stream.Read(buf,left);
Socket.SendBuf(buf,left);
end;
end;
end;
Server端(收方)
private
Tof : file;
size,count :integer;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
ServerSocket1.Active := True;
StatusBar1.SimpleText := 'Listening...';
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
buf : array [1..2048] of char;
rcvtxt : string;
left,len : integer;
begin
len := Socket.ReceiveLength;
if len<10 then
begin
rcvtxt := Socket.ReceiveText;
size := strtoint(rcvtxt);
count := 0;
AssignFile(ToF,SaveDialog1.FileName);
Rewrite(ToF, 1);
Socket.SendText('go~');
end
else
begin
left := size - count;
if sizeof(buf)<left then
begin
Socket.ReceiveBuf(buf,sizeof(buf));
BlockWrite(Tof,buf,sizeof(buf));
count := count + sizeof(buf);
Socket.SendText('go~');
end
else
begin
Socket.ReceiveBuf(buf,left);
BlockWrite(Tof,buf,left);
CloseFile(Tof);
end;
end;
end;