あるお客様から TMS Sparkle と sgcWebSockets を同時に実行できるかとのご質問をいただきました。答えは「はい」で、同じサーバーで sgcWebSockets と TMS Sparkle を実行しても問題はありません。両方とも HTTP.SYS サーバーで動作でき、単一の HTTP.SYS サーバーを起動して Sparkle と sgcWebSockets のエンドポイントを設定することができます。基本的には各パッケージで処理するエンドポイントを設定します。
sgcWebSockets は HTTP API サーバーを通じて HTTP.SYS サーバーで動作できます:
https://www.esegece.com/help/sgcWebSockets/ja/#t=Components%2FTsgcWebSocketServer_HTTPAPI.htm
以下に、sgcWebSockets と TMS Sparkle が同じ HTTP.SYS サーバーで動作する 2 つのサンプルを示します。
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 を管理者として実行してください。ポート 2001・エンドポイント "/ws" でリッスンする WebSocket サーバーが起動します。2. HelloWorldServer を実行してください。ポート 2001・エンドポイント "/rest" でリッスンする REST サーバーが起動します。
3. ws://127.0.0.1:2001/ws に WebSocket 接続を開いてください。接続後にサーバーからメッセージが届き、メッセージを送信するとサーバーが自動的に返信します。
4. http://127.0.0.1:2001/rest に HTTP 接続を開いてください。REST サーバーからのシンプルなレスポンスが表示されます。
