Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

A simple way to send files using TClientSocket & TServerSocket

Title: A simple way to send files using TClientSocket & TServerSocket Question: How can I send files using TClientSocket & TServerSocket? Sending files with TClientSocket/TServerSocket Answer: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ScktComp, ExtCtrls, StdCtrls; type TForm1 = class(TForm) Image1: TImage; Image2: TImage; ClientSocket1: TClientSocket; ServerSocket1: TServerSocket; Button1: TButton; procedure Image1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ClientSocket1Connect(Sender: TObject; Socket: TCustomWinSocket); procedure ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket); private { Private declarations } Reciving: boolean; DataSize: integer; Data: TMemoryStream; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Image1Click(Sender: TObject); begin // This is the procedure to open the socket for RECEIVING. // Button1.Click is this procedure as well. ClientSocket1.Active:= true; end; procedure TForm1.FormCreate(Sender: TObject); begin // Open the SENDING socket. ServerSocket1.Active:= true; end; procedure TForm1.ClientSocket1Connect(Sender: TObject; Socket: TCustomWinSocket); begin // Send command to start the file sending. Socket.SendText('send'); end; procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket); var s, sl: string; begin s:= Socket.ReceiveText; // If we're not in recieve mode: if not Reciving then begin // Now we need to get the length of the data stream. SetLength(sl, StrLen(PChar(s))+1); // +1 for the null terminator StrLCopy(@sl[1], PChar(s), Length(sl)-1); DataSize:= StrToInt(sl); Data:= TMemoryStream.Create; // Delete the size information from the data. Delete(s, 1, Length(sl)); Reciving:= true; end; // Store the data to the file, until we've received all the data. try Data.Write(s[1], length(s)); if Data.Size = DataSize then begin Data.Position:= 0; Image2.Picture.Bitmap.LoadFromStream(Data); Data.Free; Reciving:= false; Socket.Close; end; except Data.Free; end; end; procedure TForm1.ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket); var ms: TMemoryStream; begin // The client wants us to send the file. if Socket.ReceiveText = 'send' then begin ms:= TMemoryStream.Create; try // Get the data to send. Image1.Picture.Bitmap.SaveToStream(ms); ms.Position:= 0; // Add the length of the data, so the client // will know how much data to expect. // Append #0 so it can determine where the size info stops. Socket.SendText(IntToStr(ms.Size) + #0); // Send it (the socket owns the stream from now on). Socket.SendStream(ms); except // So only free the stream if something goes wrong. ms.Free; end; end; end; end.