A tiny .NET library to do inter-process communication (IPC) between different processes on the same machine.
A tiny .NET library to do inter-process communication (IPC) between different processes on the same machine.
Get the ZetaIpc
NuGet package.
First trying ZeroMQ to do some very small IPC between two WinForms processes on the same machine, I failed and didn't bother to dig deeper. Instead I used the phantastic C# WebServer project and quickly assembled some small wrapper.
I intentionally implemented only simple string send and receive methods, everything else is out of scope of the library. E.g. you could use Json.NET to transfer JSON within the strings between the client and the server.
To use the server (i.e. the "thing" that listens for incoming request and answers them), do something like:
var s = new IpcServer();
s.Start(12345); // Passing no port selects a free port automatically.
Console.WriteLine("Started server on port {0}.", s.Port);
s.ReceivedRequest += (sender, args) =>
{
args.Response = "I've got: " + args.Request;
args.Handled = true;
};
This starts a new background thread and continues execution.
Later, simply call
s.Stop();
to stop the server again.
To use the client (i.e. the "thing" that can send texts to the server), do something like:
var c = new IpcClient();
c.Initialize(12345);
Console.WriteLine("Started client.");
var rep = c.Send("Hello");
Console.WriteLine("Received: " + rep);
If you want a bi-directional communication between the server and client that can be started by both the client and the server, simply use the above code of the server on the client and the code of the client on the server (use different ports, of course).
This gives you two applications, each of them being server and client at the same time.
I've developed the library to start an external application from my main application. My main application acts as the client and my external application as the server.
The whole process of starting and communicating with the external application roughly follows these steps:
FreePortHelper.GetFreePort()
method on the main application, a free port number is being gathered.IpcServer
on this given port.IpcClient
to send messages to the external application and receives messages back. If you want to wait until the server has really started and is ready, you can use an event wait handle.