Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named Pipe Server & Client - No Message

Tags:

c#

named-pipes

I am trying to learn how to do Named Pipes. So I created a Server and Client in LinqPad.

Here is my Server:

var p = new NamedPipeServerStream("test3", PipeDirection.Out);
p.WaitForConnection();
Console.WriteLine("Connected!");
new StreamWriter(p).WriteLine("Hello!");
p.Flush();
p.WaitForPipeDrain();
p.Close();

Here is my Client:

var p = new NamedPipeClientStream(".", "test3", PipeDirection.In);
p.Connect();
var s = new StreamReader(p).ReadLine();
Console.Write("Message: " + s);
p.Close();

I run the server, and then the client, and I see "Connected!" appear on the server so it is connecting properly. However, the Client always displays Message: with nothing after it, so the data isn't actually travelling from server to client to be displayed. I have already tried swapping pipe directions and having the client send data to the server with the same result.

Why isn't the data being printed out in the screen in this example? What am I missing?

Thanks!

like image 473
mellamokb Avatar asked Oct 31 '25 19:10

mellamokb


1 Answers

Like L.B said, you must flush the StreamWriter. But employing the using pattern will prevent such mistakes:

using (var p = new NamedPipeServerStream("test3", PipeDirection.Out))
{
    p.WaitForConnection(); 
    Console.WriteLine("Connected!"); 
    using (var writer = new StreamWriter(p))
    {
         writer.WriteLine("Hello!");
         writer.Flush();
    }
    p.WaitForPipeDrain(); 
    p.Close();
}

In the above code, even if Flush() and Close() were omitted, everything would work as intended (since these operations are also performed when an object is disposed). Also, if any exceptions are thrown, everything will still be cleaned up properly.

like image 109
Allon Guralnek Avatar answered Nov 03 '25 10:11

Allon Guralnek