开发者

Named Pipe Server & Client - No Message

开发者 https://www.devze.com 2023-04-11 18:37 出处:网络
I am trying to learn how to do Named Pipes.So I created a Server and Client in LinqPad. Here is my Server:

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(".", "tes开发者_运维百科t3", 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 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号