3 Examples of IPC using named pipes
PipePocMsExample
This project is an example using the official Microsoft documentation.
PipePocBinClient (Client and Server)
It uses PipeTransmissionMode.Message, communication occurs by buffered read/write (bytes);
PipePocStreamReader (Client and Server)
This project is a copy of PipePocBin but it uses StreamReader and StreamWriter helpers.
My findings...
This was the example that best fit the needs of my project, and was quite simple:
The Client
NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", "testpipe",
PipeDirection.InOut, PipeOptions.None,
TokenImpersonationLevel.Impersonation);
pipeClient.Connect();
pipeClient.ReadMode = PipeTransmissionMode.Message;
while (pipeClient.IsConnected)
{
Console.Write("Ready: ");
string readline = Console.ReadLine();
byte[] resp = UnicodeEncoding.Default.GetBytes(readline);
pipeClient.Write(resp, 0, resp.Length);
StringBuilder sb = new StringBuilder();
do
{
var buffer = new byte[10];
var readBytes = pipeClient.Read(buffer, 0, buffer.Length);
sb.Append(UnicodeEncoding.Default.GetString(buffer));
}
while (!pipeClient.IsMessageComplete);
Console.WriteLine(sb.ToString().TrimEnd('\0'));
}
pipeClient.Close();
PipePoc/PipePocBinClient/Program.cs
Lines 23 to 58 in 9dcb2e1
The Server
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message);
int threadId = Thread.CurrentThread.ManagedThreadId;
// Wait for a client to connect
pipeServer.WaitForConnection();
while (pipeServer.IsConnected)
{
StringBuilder sb = new StringBuilder();
do
{
var buffer = new byte[10];
AutoResetEvent manualResetEvent = new AutoResetEvent(false);
pipeServer.BeginRead(buffer, 0, buffer.Length, (st) => {
pipeServer.EndRead(st);
manualResetEvent.Set();
}, null);
manualResetEvent.WaitOne();
sb.Append(UnicodeEncoding.Default.GetString(buffer));
}
while (!pipeServer.IsMessageComplete);
Console.WriteLine(sb.ToString());
Console.Write("Ready: ");
string readline;
do
{
readline = Console.ReadLine();
} while (string.IsNullOrEmpty(readline));
byte[] resp = UnicodeEncoding.Default.GetBytes(readline);
pipeServer.Write(resp, 0, resp.Length);
}
pipeServer.Close();
PipePoc/PipePocBinServer/Program.cs
Lines 31 to 62 in 9dcb2e1