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.

结果。

发布了319 篇原创文章 · 获赞 64 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/winniezhang/article/details/104739364