诚心请教,关于Socket传送内存流的问题 ( 积分: 200 )

  • 主题发起人 主题发起人 kelongchina
  • 开始时间 开始时间
K

kelongchina

Unregistered / Unconfirmed
GUEST, unregistred user!
一个客户端用ServerSocket,服务端用ClientSocket,然后两个的功能都是能互相下载对方的文件,我自己写的代码有问题,应该是内存流使用不当,请大家指正,谢谢

procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
str,s:string;
MyBuffer: array[0..10000] of byte; {设置接收缓冲区}
len:integer;
begin

if isdown=false then
begin
str:=socket.ReceiveText;
s:=Copy(str,1,5);
if s='11111' then
begin
m:=Tmemorystream.Create;
m.LoadFromFile(copy(str,6,length(str)));
m.Position:=0;
len:=m.Size;
self.ServerSocket1.Socket.Connections[0].SendText(inttostr(len)) ;
end;

if s='22222' then
begin
m.Position:=0;
self.ServerSocket1.Socket.Connections[0].SendStream(m);
end;
end
else
begin
if msize = 0 then {MySize为服务端发送的字节数,如果为0表示为尚未开始图象接收}
begin
// m.Position:=0;
S := Socket.ReceiveText;
msize := Strtoint(S); {设置需接收的字节数}
self.ProgressBar1.Max:= msize;
ServerSocket1.Socket.Connections[0].SendText('22222'); {发指令通知服务端开始发送图象}
end
else
begin
len := socket.ReceiveLength; {读出包长度}
ProgressBar1.Position:=ProgressBar1.Position+len;
// fillchar(MyBuffer, sizeof(MyBuffer), 0);
Socket.ReceiveBuf(MyBuffer, len); {接收数据包并读入缓冲区内}
m.Write(MyBuffer, len); {将数据写入流中}
if m.Size >= msize then {如果流长度大于需接收的字节数,则接收完毕}
begin
try
m.SaveToFile('d:/2.mp3');
finally {以下为清除工作 }

msize:=0;
//m.Position:=0;
m.Clear;
ProgressBar1.Position:=ProgressBar1.Max;
showmessage('接受完毕');
end;
end;
end;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
m:=Tmemorystream.Create;
msize:=0;
isdown:=false;
end;

procedure TForm1.ServerSocket2ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
s:string;
begin
s:=socket.ReceiveText;
if s='down' then
begin
isdown:=false;
self.ServerSocket2.Socket.Connections[0].SendText('downOK') ;
end;

if s='downOK' then
begin
isdown:=true;
self.ServerSocket1.Socket.Connections[0].SendText('11111'+'d:/1.mp3');
end;
end;

客户端和服务端因为是同样的功能,所以是同样代码,这个问题捆饶我几天了,在这里发帖子和CSDN发,都没朋友帮忙解决,希望这次大家能帮我解决下,谢谢
 
后退
顶部