Scalabium Software

SMExport advertising
Knowledge for your independence'.
Home Delphi and C++Builder tips


#116: How can I download a file from internet using sockets?

Sometime ago I posted a code sample for file downloading using WinInet.dll API of MS Internet Explorer). Today I want to post a tip for file downloading using sockets. Using sockets you can download any file from any site and no matter which browser type was used in MS Windows - Explorer, Netscape, Opera etc

The DownloadFile procedure (view below) can be used in any your project - just call with defined parameters:

procedure DownloadFile(strHost, strRemoteFileName, strLocalFileName: string;
 ClientSocket: TClientSocket);
var
  intReturnCode: Integer;
  s: string;
  szBuffer: array[0..128] of Char;
  FileOut: TFileStream;
begin
  if strRemoteFileName[1] <> '/' then
    strRemoteFileName := '/' + strRemoteFileName;

  FileOut := TFileStream.Create(strLocalFileName, fmCreate);
  try
    with ClientSocket do
    begin
      Host := strHost;
      ClientType := ctBlocking;
      Port := 80;

      try
        Open;
        {send query}
        s := 'GET ' + strRemoteFileName + '   HTTP/1.0'#13#10 +
             'Host: ' + strHost + #13#10#13#10;
        intReturnCode := Socket.SendBuf(Pointer(s)^, Length(s));

        if intReturnCode > 0 then
        begin
          {receive the answer}
          { iterate until no more data }
          while (intReturnCode > 0) do
          begin
            { clear buffer before each iteration }
            FillChar(szBuffer, SizeOf(szBuffer), 0);

            { try to receive some data }
            intReturnCode := Socket.ReceiveBuf(szBuffer, SizeOf(szBuffer));

            { if received a some data, then add this data to the result string }
            if intReturnCode > 0 then
              FileOut.Write(szBuffer, intReturnCode);
          end
        end
        else
          MessageDlg('No answer from server', mtError, [mbOk], 0);

        Close;
      except
        MessageDlg('No connection', mtError, [mbOk], 0);
      end;
    end;
  finally
    FileOut.Free
  end;
end;

To execute this procedure:

procedure TForm1.Button1Click(Sender: TObject);
begin
  DownloadFile('www.scalabium.com', '/forums.htm', 'd:\forums.htm', ClientSocket1);
end;

PS: the last parameter is ClientSocket component which you must drop on form from component pallete or create in run-time.


Published: February 14, 2001

See also
 
Paradox ActiveX
Database Information Manager
ExcelFile Viewer
Paradox Password Recovery
Word Web-stream
MAPIMail
Clarion to Text converter
DBLoad
Mail parser (ActiveX)
Excel Web-stream
 
 


Contact to webmaster

 

Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2024, Scalabium Software. All rights reserved.
webmaster@scalabium.com

SMExport/SMImport suites