Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Receive a server callback in a Snif client

Pass a client-implemented interface to a Snif service so the server can call back on the subscriber's connection. In this example a second client publishes a notice. The subscriber receives the notice while it is idle.

Define the callback and the service

uses
  System.SysUtils, StreamSec.Snic.ClassClient, StreamSec.Snif.ClassServer,
  StreamSec.Snif.ServerAttributes;

type
  {$M+}
  INoticeListener = interface
    ['{693C0846-E946-4595-B70A-466BBF8C10D9}']
    procedure OnNotice(const aText: string);
  end;

  INoticeFeed = interface
    ['{8C9C62E3-2CC6-4EB6-91B8-F8D41B0C4579}']
    function Subscribe(const aListener: INoticeListener): Boolean;
    function Publish(const aText: string): Boolean;
    function Unsubscribe: Boolean;
  end;
  {$M-}

The subscriber implements INoticeListener. The server implements the methods in INoticeFeed and uses OnNotice to send text back to the subscriber. Both interfaces have a GUID and method RTTI.

{$METHODINFO ON}
[InstanceKind(perApplication), Roles('notice')]
TNoticeFeed = class
private
  fListener: INoticeListener;
  fContextName: string;
public
  function Subscribe(const aListener: INoticeListener): Boolean;
  function Publish(const aText: string): Boolean;
  function Unsubscribe: Boolean;
end;
{$METHODINFO OFF}

perApplication gives both clients the same feed. This feed has one subscription slot. A caller needs the notice role to open the feed. See Restrict a remote Snif method by role.

Register the service and subscribe

procedure RegisterNoticeFeed;
begin
  TsnifClassServer.RegisterServerClass(TNoticeFeed);
end;

function OpenNoticeFeed(aClient: TsnicClassClient): INoticeFeed;
begin
  if not aClient.MakeInstance(TNoticeFeed.QualifiedClassName, TypeInfo(INoticeFeed), Result, '') then
    raise Exception.Create('Could not open the notice feed');
end;

Call RegisterNoticeFeed once during server startup, before adding users and starting the listener. Open two authenticated connections as in Expose a Delphi class through Snif and call it from a client. Give each user the notice role.

TNoticeListener = class(TInterfacedObject, INoticeListener)
private
  fCount: Integer;
  fLastNotice: string;
public
  procedure OnNotice(const aText: string);
  property Count: Integer read fCount;
  property LastNotice: string read fLastNotice;
end;
function SubscribeNotices(aClient: TsnicClassClient; const aListener: INoticeListener): INoticeFeed;
begin
  Result := OpenNoticeFeed(aClient);
  if not Result.Subscribe(aListener) then
    raise Exception.Create('The notice feed already has a subscriber');
end;

Create a TNoticeListener on the subscriber and keep it in an INoticeListener variable. Pass it and the connected client to SubscribeNotices and keep the returned feed proxy for unsubscribing. The server receives a callback proxy tied to that subscriber's context.

function TNoticeFeed.Subscribe(const aListener: INoticeListener): Boolean;
begin
  TMonitor.Enter(Self);
  try
    Result := Assigned(aListener) and not Assigned(fListener);
    if Result then begin
      fContextName := TsnifClassServer.CurrentContext.Name;
      fListener := aListener;
    end;
  finally
    TMonitor.Exit(Self);
  end;
end;

function TNoticeFeed.Unsubscribe: Boolean;
begin
  TMonitor.Enter(Self);
  try
    Result := Assigned(fListener) and (fContextName = TsnifClassServer.CurrentContext.Name);
    if Result then begin
      fListener := nil;
      fContextName := '';
    end;
  finally
    TMonitor.Exit(Self);
  end;
end;

The server gets the subscription owner from the calling connection's CurrentContext.Name. A second connection can publish a notice but cannot clear the subscriber's slot.

Dispatch incoming callbacks on the idle client

procedure TNoticeListener.OnNotice(const aText: string);
begin
  fLastNotice := aText;
  Inc(fCount);
end;

function PumpNoticeCallback(aClient: TsnicClassClient): Boolean;
begin
  if (aClient.Connection = nil) or not aClient.Connection.IsActive then
    raise Exception.Create('The subscriber connection is closed');
  Result := aClient.Connection.HasData;
  if Result then
    aClient.HandleRequest;
end;

Have the thread that owns the subscriber connection call PumpNoticeCallback when idle. HasData checks for a complete incoming message. HandleRequest invokes the listener on that thread and sends its reply. Give that thread exclusive use of the connection while pumping. If a worker owns the pump, hand any UI update to the UI thread and read listener state under a lock or after joining the worker.

Publish from a second client

function TNoticeFeed.Publish(const aText: string): Boolean;
var
  lListener: INoticeListener;
begin
  TMonitor.Enter(Self);
  try
    if (fListener = nil) or (fContextName = TsnifClassServer.CurrentContext.Name) then
      Exit(False);
    lListener := fListener;
  finally
    TMonitor.Exit(Self);
  end;

  try
    lListener.OnNotice(aText);
    Result := True;
  except
    TMonitor.Enter(Self);
    try
      if fListener = lListener then begin
        fListener := nil;
        fContextName := '';
      end;
    finally
      TMonitor.Exit(Self);
    end;
    raise;
  end;
end;

On the publisher's connection, call OpenNoticeFeed and then Publish('Document ready'). A True result means the subscriber's OnNotice method returned. Its LastNotice now contains Document ready. The server releases the feed's lock before making this synchronous call so it can wait for the subscriber's reply. A callback failure clears the failed subscription and propagates to the publisher.

When finished, stop publishing and join any callback pump before using the subscriber connection to call Unsubscribe. It returns True when the slot is cleared. A subsequent Publish returns False while the slot is empty. Release the proxies before freeing the clients. The subscriber component keeps its registered callback objects until the component is freed.

Reference

TsnifClassServer · TsnicClassClient · StreamSec.Snif.ClassServer · StreamSec.Snic.ClassClient · StreamSec.Snif.ServerAttributes

Related tasks