Socket编程问题 ( 积分: 25 )

  • 主题发起人 主题发起人 午午
  • 开始时间 开始时间

午午

Unregistered / Unconfirmed
GUEST, unregistred user!
这是我在网上当到的一个点对点的文件传输程序,我该了一下。现在传输文件的时候有时能传输成功(传输成功了也有可能会打不开,说文件已损坏)主要代码我贴出来,大家帮我看看
服务器端:
procedure TfrmScktMain.ServerSocketClientRead(Sender: TObject;
Socket: TCustomWinSocket);//从客户端读取信息
Var
//i:integer;
sTemp:string;
bufRecv:Pointer;
iNum:integer;
begin
//将从客户端读取的信息添加到Memo1中
SendSession:=Socket;
if bReadText then
begin
sTemp:=Socket.ReceiveText;
case sTemp[1] of
MP_QUERY:
begin
SaveDialog1.FileName:=Copy(sTemp,2,Length(STemp));
if SaveDialog1.Execute then
begin
ServerSocket.Socket.Connections[0].SendText(MP_ACCEPT);
fsRecv := TMemoryStream.Create;
end
else
ServerSocket.Socket.Connections[0].SendText(MP_REFUSE+' ');
end;
MP_FILEPROPERTY:
begin
//Size:=StrToInt(Copy(sTemp,2,Length(sTemp)));
ServerSocket.Socket.Connections[0].SendText(MP_NEXTWILLBEDATA);
end;
MP_NEXTWILLBEDATA:
begin
bReadText:=false;
ServerSocket.Socket.Connections[0].SendText(MP_DATA);
end;
MP_END:
begin
fsRecv.Free;
bReadText:=true;
end;
MP_ABORT:
begin
fsRecv.Free;
bReadText:=true;
end;
MP_CHAT:
begin
Memo1.Lines.Add(Copy(sTemp,2,Length(STemp)));
end;
end;{of case}
end
else
begin
try
GetMem(bufRecv,iBYTEPERSEND);
iNum := Socket.ReceiveBuf(bufRecv^,iBYTEPERSEND);
fsRecv.WriteBuffer(bufRecv^, iNum);
finally
FreeMem(bufRecv);
end;{of try}
bReadText:=true;
if iNum = iBYTEPERSEND THEN
begin
ServerSocket.Socket.Connections[0].SendText(MP_NEXTWILLBEDATA);
end
else
begin
fsRecv.SaveToFile(SaveDialog1.FileName);
fsRecv.Free;
ServerSocket.Socket.Connections[0].SendText(MP_END);
Memo1.Lines.Add('数据接收已完毕!');
end;
end;
end.
客户端:
procedure TfrmClientMain.ClientSocketRead(Sender: TObject;
Socket: TCustomWinSocket);//接受服务器端的回复
Var
sRecv:string;
iNum:integer;
bufSend:pointer;
begin
sRecv:=Socket.ReceiveText;
Case sRecv[1] of
MP_REFUSE: ShowMessage('Faint,be refused!');
MP_ACCEPT:
begin
fsSend:=TMemoryStream.Create;//(OpenDialog1.FileName,fmOpenRead);
fsSend.LoadFromFile(OpenDialog1.FileName);
ClientSocket.Socket.SendText(MP_FILEPROPERTY+IntToStr(Trunc(fsSend.Size/iBYTEPERSEND)+1));
fsSend.Seek(0, soFromBeginning);//将传输的起始位置置到filestream的最开始位置
end;
MP_NEXTWILLBEDATA:
begin
Socket.SendText(MP_NEXTWILLBEDATA);
end;
MP_DATA:
begin
try
GetMem(bufSend,iBYTEPERSEND);//在内存在开辟空间,指针bufSend指向这段大小为fsSend.Size的内存
iNum := fsSend.Read(bufSend^,iBYTEPERSEND);
ClientSocket.Socket.SendBuf(bufSend^,iNum);//向服务端发指针(内存数据)
finally
FreeMem(bufSend);
end;{of try}
end;
MP_END:
begin
fsSend.Free;
Memo1.Lines.Add('数据传送已完毕!');
end;
MP_ABORT:
begin
fsSend.Free;
end;
MP_CHAT:
begin
Memo1.Lines.Add(Copy(sRecv,2,Length(sRecv)));
end;
end;{of case}
end;
 
这么复杂?

看着头晕哦!
 
代码太多了?
 
有掉包的嫌疑
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
后退
顶部