WebSocket 与 TMS Sparkle

· 组件

一位客户询问 TMS SparklesgcWebSockets 是否可以共同运行,答案是肯定的,在同一台服务器上同时运行 sgcWebSockets 和 TMS Sparkle 完全没有问题。两者都可以使用 HTTP.SYS 服务器运行,您可以运行单个 HTTP.SYS 服务器并将端点配置为分别由 Sparkle 和 sgcWebSockets 处理,互不干扰。基本上,您在每个包中配置各自处理哪个端点即可。

sgcWebSockets 可以通过 HTTP API 服务器在 HTTP.SYS 服务器上运行:

https://www.esegece.com/help/sgcWebSockets/#t=Components%2FTsgcWebSocketServer_HTTPAPI.htm

以下是 2 个示例,展示 sgcWebSockets 和 TMS Sparkle 如何在同一个 HTTP.SYS 服务器上运行。

sgcWebSockets 示例

program sgcWSServer;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils,
  sgcWebSocket, sgcWebSocket_Classes,
  sgcWebSocket_Server_HTTPAPI;
type
  TsgcServerClass = class
    public
      procedure OnConnectEvent(Connection: TsgcWSConnection);
      procedure OnMessageEvent(Connection: TsgcWSConnection; const Text: String);
  end;
procedure TsgcServerClass.OnConnectEvent(Connection: TsgcWSConnection);
begin
   Connection.WriteData('Hello From Server.');
end;
procedure TsgcServerClass.OnMessageEvent(Connection: TsgcWSConnection; const
    Text: String);
begin
  Connection.WriteData(Text);
end;
var
  oServer: TsgcWebSocketServer_HTTPAPI;
  oConnection: TsgcServerClass;
begin
  try
    oServer := TsgcWebSocketServer_HTTPAPI.Create(nil);
    oConnection := TsgcServerClass.Create;
    Try
      oServer.Bindings.NewBinding('127.0.0.1', 2001, '/ws/');
      oServer.OnConnect := oConnection.OnConnectEvent;
      oServer.OnMessage := oConnection.OnMessageEvent;
      oServer.Active := True;
      WriteLn('sgcWebSockets Server started at ws://127.0.0.1:2001/ws');
      while oServer.Active do
        Sleep(10);
    Finally
      oConnection.Free;
      oServer.Free;
    End;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

TMS Sparkle 示例

program HelloWorldServer;
{$APPTYPE CONSOLE}
uses
  System.SysUtils,
  Sparkle.HttpServer.Context,
  Sparkle.HttpServer.Module,
  Sparkle.HttpSys.Server;
type
  THelloWorldModule = class(THttpServerModule)
    public procedure ProcessRequest(const C: THttpServerContext); override;
  end;
procedure THelloWorldModule.ProcessRequest(const C: THttpServerContext);
begin
  C.Response.StatusCode := 200;
  C.Response.ContentType := 'text/plain';
  C.Response.Close(TEncoding.UTF8.GetBytes('Hello, World!'));
end;
const
  ServerUrl = 'http://127.0.0.1:2001/rest';
var
  Server: THttpSysServer;
begin
  Server := THttpSysServer.Create;
  try
    Server.AddModule(THelloWorldModule.Create(ServerUrl));
    Server.Start;
    WriteLn('Hello World Server started at ' + ServerUrl);
    WriteLn('Press Enter to stop');
    ReadLn;
  finally
    Server.Free;
  end;
end. 

编译后的示例

按照以下说明运行示例:

1.管理员身份运行 sgcWSServer。将启动一个 WebSocket 服务器,监听端口 2001,端点为 "/ws"。

2. 运行 HelloWorldServer。将启动一个 REST 服务器,监听端口 2001,端点为 "/rest"。

3. 打开 WebSocket 连接至 ws://127.0.0.1:2001/ws。连接后您将收到来自服务器的消息,发送任意消息后服务器将自动回显。

4. 打开 HTTP 连接至 http://127.0.0.1:2001/rest。将显示 REST 服务器的简单响应。