22

我有两个通过命名管道相互通信的 .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 让服务器打印我发送的消息就好了,但是当它循环回来再次收听时,它便便。

4

3 回答 3

20

I'll post my code that seems to work - I was curious since I never did anything with pipes. I didn't find the class you name for the server-side in the relevant namespace, so here's the code based on the NamedPipeServerStream. The callback stuff is just because I couldn't be bothered with two projects.

NamedPipeServerStream s = new NamedPipeServerStream("p", PipeDirection.In);
Action<NamedPipeServerStream> 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();
  }
}

And the client does this:

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

I can repeat above block multiple times with the server running, no prob.

于 2009-05-21T22:49:51.420 回答
12

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

while (true)
{
    try
    {
        _pipeServer.WaitForConnection();
        break;
    }
    catch (IOException)
    {
        _pipeServer.Disconnect();
        continue;
    }            
 }
于 2012-02-28T15:21:54.537 回答
-3

我遇到了同样的问题 - 这是由 Using...End Using 处理服务器的 StreamReader 引起的,这也取消了 NamedPipeServerStream。解决方案就是不要使用...结束使用它并信任垃圾收集器。

于 2019-10-29T10:46:54.553 回答