3
votes

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!

2
According to the StreamReader.ReadLine docs it will return null if end of stream is reached. It may be that at the time you do the ReadLine there is no data in the pipe and the stream is empty. You may want to loop back around and try again to read if s is null. - user957902

2 Answers

3
votes

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.

2
votes

Change your server code as follows:

StreamWriter wr = new StreamWriter(p);
wr.WriteLine("Hello!\n");
wr.Flush();

your string doesn't get flushed in StreamWriter