Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi 2009: How to communicate between Windows service & desktop application under Vista?

How can a desktop application communicate with a Windows service under Vista/Windows2008/Windows7? The application needs to send small strings to the service and receive string responses back. Both are written in Delphi 2009. (Please provide sample code also)

like image 717
Vic Avatar asked Aug 11 '09 12:08

Vic


2 Answers

The way to go is named pipes, you'll probably have to take a look at the communication across different Integrity levels.

This article explores how to do this in vista. Although it's written in c++ it's just basic Windows API calls, so it should translate fast enough to Delphi.

If you want to search for more on this subject, this communication is called Inter Process Communication, but a better search term is IPC.

like image 98
Davy Landman Avatar answered Oct 13 '22 22:10

Davy Landman


Using Indy you can relatively easy create a TCP connection between your apps. Especially if you only need to send string messages. For the client (in your case the desktop application) it's basically

var
  Client : TIdTCPClient;
...
Client.Host := 'localhost';
Client.Port := AnyFreePortNumber;
Client.Connect;
Client.IOHandler.Writeln (SomeString);
Response := Client.Readln;
...
Client.Disconnect;

For the server (would be the service in your case)

var
  Server  : TIdTCPServer;
  Binding : TIdSocketHandle;
...
Server.DefaultPort := SameFreePortNumberAsInClient;
Binding := Server.Bindings.Add;
Binding.IP := '127.0.0.1';    
Binding.Port := Server.DefaultPort;
Server.OnConnect := HandleConnection;
Server.OnDisconnect := HandleDisconnection;
Server.OnExecute := HandleCommunication;
Server.Active := True;

Just implement the HandleCommunication method. It is called whenever the client decides to send something. Example:

procedure MyClass.HandleCommunication (AContext : TIdContext);
var
  Request : String;
begin
  Request := AContext.Connection.IOHandler.Readln;
  if (Request = Command1) then
    HandleCommand1
  else if (Request = Command2) then
    HandleCommand2
  ...
end;

IIRC a service is only allowed to have a graphical user interface OR have network access, so this might be a problem if your service needs a GUI (which you should avoid anyway, see this question). I don't know how this is handled in Windwos Vista and later though.

like image 32
jpfollenius Avatar answered Oct 13 '22 23:10

jpfollenius