WAMP 组件最常见的用途是客户端从服务器请求方法,服务器向客户端发送响应。客户端只需发送方法名称,并/或传递服务器计算结果所需的一些参数。服务器处理请求,如果成功,则向客户端发送包含结果的响应;如果发生任何错误,服务器向客户端发送错误响应。
如您所见,只有一个请求和一个响应(成功或失败)。
示例:服务器有一个名为 GetTime 的方法,每次客户端请求此方法时,服务器返回服务器时间。
WAMP 服务器
procedure OnServerCall(Connection: TsgcWSConnection; const CallId, ProcUri, Arguments: string);
begin
if ProcUri = 'GetTime' then
oServerWAMP.CallResult(CallId, FormatDateTime('yyyymmdd hh:nn:ss', Now))
else
oServer.WAMP.CallError(CallId, 'Unknown method');
end;
oServer := TsgcWebSocketServer.Create(nil);
oServer.Port := 80;
oServerWAMP := TsgcWSPServer_WAMP.Create(nil);
oServerWAMP.OnCall := OnServerCallEvent;
oServerWAMP.Server := oServer;
oServer.Active := True;
WAMP 客户端
procedure OnCallResultClient(Connection: TsgcWSConnection; CallId, Result: string);
begin
ShowMessage(Result);
end;
procedure OnCallErrorClient(Connection: TsgcWSConnection; const Error: string);
begin
ShowMessage(Error);
end;
oClient := TsgcWebSocketClient.Create(nil);
oClient.Host := '127.0.0.1';
oClient.Port := 80;
oClientWAMP := TsgcWSPClient_WAMP.Create(nil);
oClientWAMP.OnCallResult := OnCallResultClient;
oClientWAMP.OnCallError := OnCallErrorClient;
oClientWAMP.Client := oClient;
oClient.Active := True;
// After client has connected, request GetTime from server
oClientWAMP.Call('GetTime');