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