AutoServer sample (Delphi)

Overview

This sample demostrates a practical example of how a client can control the server when they are both running locally. This is useful if you want to provide a simple standalone solution which is easily upgradeable to work over the network (or you might want to provide both options).

Getting Started

To try this sample, compile both server and client projects and then run the client. On startup, the client will look for an existing server window with a predefined name and start the server if necessary.

Examine the code

  • Both projects present a standard Remoting SDK client and server, there is nothing special from that point of view. But look how the client controls the server:
  fServerHandle := FindWindow(nil, 'AutoServer - Server');

  if (fServerHandle = 0) then begin
    Log('No server found.');
    AutoShutDownServer := TRUE;

    // Starts it
    serverfilename := ExtractFilePath(Application.ExeName) + 'AutoServer.exe';
    Log('Attempting to start a server ''' + serverfilename + '''');
    Res := ShellExecute(0, 'open', PChar(serverfilename), nil, nil, SW_NORMAL);
    if res < 33 then begin
      Log(SysErrorMessage(Res));
      exit;
    end
    else
      Log('Waiting for the server to start ...');
    // Waits half a second. Not the best implementation but it's just to give an idea
    Sleep(500);

    Log('Searching for a server ...');
    fServerHandle := FindWindow(nil, 'AutoServer - Server');
    if (fServerHandle = 0) then
      Log('The server could not be started!')
    else
      Log('The server has been started successfully');
  end
  else begin
    Log('The server is up and running already');
    AutoShutDownServer := FALSE;
  end;
  • To demonstrate the client-server communication the server offers the GetEnvironment method which returns the value of an environment variable.
function TAutoServerService.GetEnvironment(const Environment: UnicodeString): UnicodeString;
begin
  Result := GetEnvironmentVariable(Environment);
end;