线程Socket传送文件的客户端和服务端源代码

  • A+
所属分类:[开发技巧]

一.客户端:

1.Form上放一个ClientSocket1,OpenDialog1,button1

2.ClientSocket1属性设置:
Active : False
ClientType : ctBlocking
Host : '127.0.0.1'
Port : 5998

3.button1事件:
procedure TForm1.Button1Click(Sender: TObject);
Var
s : TWinSocketStream;
f : TFileStream;
begin
If Not OpenDialog1.Execute Then Exit;
ClientSocket1.Open;
s := TWinSocketStream.Create(ClientSocket1.Socket, 60000);
f := TFileStream.Create(OpenDialog1.FileName, fmShareDenyWrite);
Try
s.CopyFrom(f, 0);
Finally
s.Free;
f.Free;
ClientSocket1.Close;
End;
end;

----------------------------------------------

二.服务端:

1.Form上放一个ServerSocket1

2.ServerSocket1属性设置:
Active : True
Port : 5998
ServerType : stThreadBlocking

3.定义客户端线程类:
TClientThread = Class(TServerClientThread)
Private
Public
Procedure ClientExecute; override;
End;

Procedure TClientThread.ClientExecute;
Var
ReceiveBuffer : Array[0..4095] Of Char;
SocketStream : TWinSocketStream;
BytesRead : Integer;
F : TFileStream;
Begin
While Not Terminated And ClientSocket.Connected Do
Begin
try
SocketStream := TWinSocketStream.Create(ClientSocket, 60000);
F := TFileStream.Create('c:\afile.exe', fmCreate);
try
FillChar(ReceiveBuffer, 10, 0);
If SocketStream.WaitForData(5000) Then
Repeat
BytesRead := SocketStream.Read(ReceiveBuffer,SizeOf(ReceiveBuffer));
if BytesRead = 0 then
ClientSocket.Close
Else
F.WriteBuffer(ReceiveBuffer, BytesRead);
Until Not SocketStream.WaitForData(2000);
finally
SocketStream.Free;
ClientSocket.Close;
f.Free;
end;
except
end;
End;
End;

4.ServerSocket1的OnGetThread事件代码:
procedure TForm1.ServerSocket1GetThread(Sender: TObject;
ClientSocket: TServerClientWinSocket;
var SocketThread: TServerClientThread);
begin
SocketThread := TClientThread.Create(False, ClientSocket);
end;

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
广告也精彩
avatar
广告也精彩

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: