Interapplication Communication with Named Pipes
// December 13th, 2009 // Useful Code
Ever make two separate applications but need them to be able to send information back and forth. Say an Instant Messenger and a Business app which need direct integration between one another. Named pipes is a pretty simple solution to achieve this. .NET 3.5 has made this much simpler by including Named Pipes in its release, this used to be real nasty when trying to achieve this in any other language then C++.
//Application
using System;
using System.IO;
using System.IO.Pipes;
class Program
{
/// <summary>
/// MAIN APPLICATION THREAD
/// </summary>
/// <param name="args">NOTHING IS ACCEPTED HERE</param>
static void Main(string[] args)
{
//HOLDS THE SECLECTION A USER MAKES AS TO WHAT THEY WANT TO RUN
string tmpSelection = string.Empty;
//ASK THE USER WHAT THEY WANT TO DO
Console.Write("Please Enter A Selection 1(Server) or 2(Client): ");
tmpSelection = Console.ReadLine();
//CLEAR THE SCREEN AND BEGIN RUNNING THE USERS SELECTION
Console.Clear();
if (tmpSelection == "1")
{
//START A PIPE SERVER
pipeServer();
}
else if (tmpSelection == "2")
{
//START A PIPE CLIENT
pipeClient();
}
else
{
//LET THE USER KNOW THEY HAVE MADE AN INVALID SELECTION
Console.WriteLine("Invalid selection made. This app will now close.");
Console.ReadLine();
}
}
/// <summary>
/// RUNS A PIPE CLIENT FOR SENDING MESSAGES
/// </summary>
private static void pipeClient()
{
//LET THE USER KNOW WHAT IS GOING ON
Console.WriteLine("Starting Client!");
//LOOP FOREVER FOR TESTING PURPOSES
while (true)
{
//CREATE A CONNECTION TO A NAMED PIPE ON THE LOCAL MACHINE NAMED testPipe
using (NamedPipeClientStream tmpPipe = new NamedPipeClientStream(".", "testPipe", PipeDirection.Out))
{
string tmpSendMessage;
//GET SOME TEXT TO SEND THROUGH THE PIPE
Console.Write("Enter Some Text To Send: ");
tmpSendMessage = Console.ReadLine();
//SEND THE MESSAGE THROUGH THE PIPE
tmpPipe.Connect();
using (TextWriter tmpWriter = new StreamWriter(tmpPipe))
{
tmpWriter.WriteLine(tmpSendMessage);
}
}
}
}
/// <summary>
/// RUNS A PIPE SERVER FOR ACCEPTING MESSAGES
/// </summary>
private static void pipeServer()
{
//LET THE USER KNOW WHAT IS GOING ON
Console.WriteLine("Starting Server!");
//LOOP FOREVER FOR TESTING PURPOSES
while (true)
{
//CREATE A NAMED PIPE ON THE LOCAL MACHINE NAMED testPipe
using (NamedPipeServerStream tmpPipe = new NamedPipeServerStream("testPipe", PipeDirection.In))
{
//READ THE DATA ON THE PIPE
tmpPipe.WaitForConnection();
using (TextReader tmpReader = new StreamReader(tmpPipe))
{
Console.WriteLine(tmpReader.ReadLine());
}
}
}
}
}
Michael E. Chancey Jr. Software Engineer Extraordinaire