Delphi2009的Indy全接触之HTTP篇

来源:互联网 发布:下载java软件 编辑:程序博客网 时间:2024/06/05 02:33
实现功能:启动一个Http服务。
如下图所示建立工程:

代码如下:
  1. unit HttpUnit;
  2. interface
  3. uses
  4.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  5.   Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer,
  6.   IdHTTPServer, IdContext;
  7. type
  8.   TForm1 = class(TForm)
  9.     IdHTTPServer1: TIdHTTPServer;
  10.     procedure FormCreate(Sender: TObject);
  11.     procedure IdHTTPServer1CommandGet(AContext: TIdContext;
  12.       ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
  13.   private
  14.     { Private declarations }
  15.   public
  16.     { Public declarations }
  17.   protected
  18.     FData: string;
  19.   end;
  20. var
  21.   Form1: TForm1;
  22. implementation
  23. {$R *.dfm}
  24. type
  25.   TSlowStream = class(TFileStream)
  26.   public
  27.     function Read(var Buffer; Count: Longint): Longint; override;
  28.   end;
  29. procedure TForm1.FormCreate(Sender: TObject);
  30. var
  31.   i: Integer;
  32. begin
  33.   IdHTTPServer1.DefaultPort := 6001;
  34.   IdHTTPServer1.Active := True;
  35.   SetLength(FData, 1024);
  36.   for i := 1 to Length(FData) do begin
  37.     FData[i] := Chr(i mod 256);
  38.   end;
  39. end;
  40. function TSlowStream.Read(var Buffer; Count: Integer): Longint;
  41. begin
  42.   Result := inherited Read(Buffer, Count);
  43.   Sleep(Count div 2);
  44. end;
  45. procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
  46.   ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
  47. begin
  48.   AResponseInfo.ContentStream := TSlowStream.Create('C:/abc.txt', fmOpenRead);
  49. end;
  50. end.
在C盘下建立文本文件abc.txt,内容如下:
  1. sdasdasd
  2. <br>
  3. asdasd
  4. <br>
  5. <input type="text" value="aaa">
启动Delphi程序,访问如下的地址即可:  http://localhost:6001/
原创粉丝点击