System.IO.Exception:管道已损坏

我有两个.NET应用程序通过命名管道相互通信。 第一次发送时一切都很好,但是在发送第一条消息之后,服务器将再次监听, WaitForConnection()方法抛出System.IO.Exception ,消息管道已断开。
为什么我在这里得到这个例外? 这是我第一次使用管道,但类似的模式在过去使用套接字对我有用。

代码啊!
服务器:

 using System.IO.Pipes; static void main() { var pipe = new NamedPipeServerStream("pipename", PipeDirection.In); while (true) { pipe.Listen(); string str = new StreamReader(pipe).ReadToEnd(); Console.Write("{0}", str); } } 

客户:

 public void sendDownPipe(string str) { using (var pipe = new NamedPipeClientStream(".", "pipename", PipeDirection.Out)) { using (var stream = new StreamWriter(pipe)) { stream.Write(str); } } } 

第一次调用sendDownPipe让服务器打印我发送的消息就好了,但是当它再循环回来再次监听时,它就会大便。

我会发布似乎有效的代码 – 我很好奇,因为我从未对管道做过任何事情。 我没有在相关命名空间中找到您为服务器端命名的类,因此这里是基于NamedPipeServerStream的代码。 回调的原因只是因为我不能为两个项目烦恼。

 NamedPipeServerStream s = new NamedPipeServerStream("p", PipeDirection.In); Action a = callBack; a.BeginInvoke(s, ar => { }, null); ... private void callBack(NamedPipeServerStream pipe) { while (true) { pipe.WaitForConnection(); StreamReader sr = new StreamReader(pipe); Console.WriteLine(sr.ReadToEnd()); pipe.Disconnect(); } } 

客户这样做:

 using (var pipe = new NamedPipeClientStream(".", "p", PipeDirection.Out)) using (var stream = new StreamWriter(pipe)) { pipe.Connect(); stream.Write("Hello"); } 

我可以在服务器运行时多次重复上面的块,没有概率。

当我在客户端断开连接后从服务器调用pipe.WaitForConnection()时,问题就出现了。 解决方案是捕获IOException并调用pipe.Disconnect(),然后再次调用pipe.WaitForConnection():

 while (true) { try { _pipeServer.WaitForConnection(); break; } catch (IOException) { _pipeServer.Disconnect(); continue; } }