天天看點

tms sparkle建立server以及module執行個體

1、使用wizard建立sparkle伺服器。

2、建立unit1、unit2、unit3單元檔案。

unit Unit1;

interface

uses {...}
  System.SysUtils, Sparkle.HttpServer.Module, Sparkle.HttpServer.Context;//必須引用的單元

type
  TSimpleModule = class(THttpServerModule)//simple類
  public
    procedure ProcessRequest(const C: THttpServerContext); override;
  end;

implementation

procedure TSimpleModule.ProcessRequest(const C: THttpServerContext);//這裡實作response功能
begin
  C.Response.StatusCode := 200;
  C.Response.ContentType := 'text/plain';
  C.Response.Close(TEncoding.UTF8.GetBytes('Test123'));//response的内容
end;

end.
           
unit Unit2;

interface

uses {...}
  System.SysUtils, Sparkle.HttpServer.Module, Sparkle.HttpServer.Context;

type
  TSecondModule = class(THttpServerModule)//second類
  public
    procedure ProcessRequest(const C: THttpServerContext); override;
  end;

implementation

procedure TSecondModule.ProcessRequest(const C: THttpServerContext);
begin
  C.Response.StatusCode := 200;
  C.Response.ContentType := 'text/plain';
  C.Response.Close(TEncoding.UTF8.GetBytes('Test456'));//response的内容
end;

end.
           
unit Unit3;

interface

uses {...}
  System.SysUtils, Sparkle.HttpServer.Module, Sparkle.HttpServer.Context;

type
  TThirdModule = class(THttpServerModule)//third類
  public
    procedure ProcessRequest(const C: THttpServerContext); override;
  end;

implementation

procedure TThirdModule.ProcessRequest(const C: THttpServerContext);
begin
  C.Response.StatusCode := 200;
  C.Response.ContentType := 'text/plain';
  C.Response.Close(TEncoding.UTF8.GetBytes('Test789'));//respose的内容
end;

end.
           

3、在server單元中建立addmudule方法中并實作。

unit Server;

interface

uses
  System.SysUtils, Sparkle.Middleware.Cors, Sparkle.Middleware.Compress,
  Sparkle.HttpSys.Server, Sparkle.HttpServer.Context, Sparkle.HttpServer.Module,
  Sparkle.HttpServer.Dispatcher;

procedure StartServer;

procedure StopServer;

procedure AddModules(Dispatcher: THttpDispatcher);//手工添加

implementation

uses
   System.IOUtils, Unit1, Unit2, Unit3;//引用

var
  SparkleServer: THttpSysServer;

procedure AddModules(Dispatcher: THttpDispatcher);
begin
  Dispatcher.AddModule(TSimpleModule.Create('http://host:2001/simple/'));//第一module
  Dispatcher.AddModule(TSecondModule.Create('http://host:2001/second/'));//第二module
  Dispatcher.AddModule(TThirdModule.Create('http://host:2001/third/'));//第三module
end;

procedure StartServer;
var
  Module: TAnonymousServerModule;
begin
  if Assigned(SparkleServer) then
    Exit;

  SparkleServer := THttpSysServer.Create;
  AddModules(SparkleServer.Dispatcher);//注冊并加載新的子產品
  SparkleServer.AddModule(Module);
  SparkleServer.Start;
end;

procedure StopServer;
begin
  FreeAndNil(SparkleServer);
end;

initialization
  SparkleServer := nil;

finalization
  StopServer;

end.
           

結果。

tms sparkle建立server以及module執行個體
tms sparkle建立server以及module執行個體
tms sparkle建立server以及module執行個體

繼續閱讀