Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sample on NamedPipeServerStream vs NamedPipeServerClient having PipeDirection.InOut needed

Tags:

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?

like image 904
Nat Avatar asked Feb 02 '12 14:02

Nat


People also ask

What do you know about a pipe and when is it used what is a named pipe?

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.

What is System IO pipes?

NamedPipeClientStream Class (System.IO.Pipes)Exposes a Stream around a named pipe, which supports both synchronous and asynchronous read and write operations.


1 Answers

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);   } } 
like image 86
Matt Avatar answered Oct 23 '22 14:10

Matt