I'm looking for a good sample where NamedPipeServerStream and NamedPipeServerClient can send messages to each other (when PipeDirection = PipeDirection.InOut for both). For now I found only this msdn article. But it describes only server. Does anybody know how client connecting to this server should look like?
A named pipe is a one-way or duplex pipe that provides communication between the pipe server and some pipe clients. A pipe is a section of memory that is used for interprocess communication. A named pipe can be described as first in, first out (FIFO); the inputs that enter first will be output first.
NamedPipeClientStream Class (System.IO.Pipes)Exposes a Stream around a named pipe, which supports both synchronous and asynchronous read and write operations.
What happens is the server sits waiting for a connection, when it has one it sends a string "Waiting" as a simple handshake, the client then reads this and tests it then sends back a string of "Test Message" (in my app it's actually the command line args).
Remember that the WaitForConnection
is blocking so you probably want to run that on a separate thread.
class NamedPipeExample { private void client() { var pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.None); if (pipeClient.IsConnected != true) { pipeClient.Connect(); } StreamReader sr = new StreamReader(pipeClient); StreamWriter sw = new StreamWriter(pipeClient); string temp; temp = sr.ReadLine(); if (temp == "Waiting") { try { sw.WriteLine("Test Message"); sw.Flush(); pipeClient.Close(); } catch (Exception ex) { throw ex; } } }
Same Class, Server Method
private void server() { var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4); StreamReader sr = new StreamReader(pipeServer); StreamWriter sw = new StreamWriter(pipeServer); do { try { pipeServer.WaitForConnection(); string test; sw.WriteLine("Waiting"); sw.Flush(); pipeServer.WaitForPipeDrain(); test = sr.ReadLine(); Console.WriteLine(test); } catch (Exception ex) { throw ex; } finally { pipeServer.WaitForPipeDrain(); if (pipeServer.IsConnected) { pipeServer.Disconnect(); } } } while (true); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With