One extremely interesting feature that modern applications are using is the Interprocess communication (IPC). It is a really important especially for designing a well established architecture having in mind the extendability. In this tutorial we will see a simple IPC made with Named Pipes. Keep in mind that the following is just an example and should not be used in production.
For this example, we will use the nuget package IPC.NamedPipe which is also available open-source on github.
Our example will be … a console chat between two application instances. First of all we create a new C# console application and import the IPC.NamedPipe package. Afterwards we simple add the following code.
class Program
{
private static void OnReceived(PipeMessage message)
{
if (message.GetPayloadType() == PipeMessageType.PMTString)
{
Console.WriteLine("[R]{S}-" + (string)message.GetPayload());
}
if (message.GetPayloadType() == PipeMessageType.PMTByte)
{
var data = (byte[])message.GetPayload();
Console.WriteLine("[R]{B}-" + BitConverter.ToString((byte[])data));
}
}
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("Error: Missing Parameters");
Console.WriteLine(" ex: ./application.exe [local_pipe_name] [remote_pipe_name] [remote_host]");
Console.WriteLine(" : - remote_host should be \".\" for localhost");
return;
}
IPC.NamedPipe.Node node = new IPC.NamedPipe.Node(args[0], args[1], args[2], OnReceived);
if (node.Start() == false)
throw new Exception("Error: Could not create the named pipe!");
while (true)
{
string r = Console.ReadLine();
if (!string.IsNullOrEmpty(r))
node.Send(r);
}
}
}
Now… to run the example just build and open two CMD.
Run one instance of the application per CMD using the following argsCMD:> MyApplication "instance1" "instance2" "."
CMD:> MyApplication "instance1" "instance2" "."
Ok… done.. type something in the first instance and you will see it in the other one… btw this can also work with different PCs in the same local network by putting in the last argument the correct hostname… Enjoy!
Thanks!