Named Pipe Server & Client - No Message

笑着哭i 提交于 2019-12-07 15:00:47

问题


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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7692259/named-pipe-server-client-no-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!