C# 需要 PipeDirection.InOut 的 NamedPipeServerStream 与 NamedPipeServerClient 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9114053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sample on NamedPipeServerStream vs NamedPipeServerClient having PipeDirection.InOut needed
提问by Nat
I'm looking for a good sample where NamedPipeServerStream and NamedPipeServerClient can send messages to each other (when PipeDirection = PipeDirection.InOut for both). For now I found only this msdn article. But it describes only server. Does anybody know how client connecting to this server should look like?
我正在寻找一个很好的示例,其中 NamedPipeServerStream 和 NamedPipeServerClient 可以相互发送消息(当 PipeDirection = PipeDirection.InOut 时)。现在我只找到了这篇 msdn 文章。但它只描述了服务器。有人知道连接到该服务器的客户端应该是什么样子吗?
采纳答案by Matt
What happens is the server sits waiting for a connection, when it has one it sends a string "Waiting" as a simple handshake, the client then reads this and tests it then sends back a string of "Test Message" (in my app it's actually the command line args).
发生的事情是服务器等待连接,当它有一个连接时,它发送一个字符串“Waiting”作为一个简单的握手,然后客户端读取它并测试它然后发送回一个“测试消息”字符串(在我的应用程序中它是实际上是命令行参数)。
Remember that the WaitForConnectionis blocking so you probably want to run that on a separate thread.
请记住,WaitForConnection正在阻塞,因此您可能希望在单独的线程上运行它。
class NamedPipeExample
{
private void client() {
var pipeClient = new NamedPipeClientStream(".",
"testpipe", PipeDirection.InOut, PipeOptions.None);
if (pipeClient.IsConnected != true) { pipeClient.Connect(); }
StreamReader sr = new StreamReader(pipeClient);
StreamWriter sw = new StreamWriter(pipeClient);
string temp;
temp = sr.ReadLine();
if (temp == "Waiting") {
try {
sw.WriteLine("Test Message");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
}
Same Class, Server Method
相同的类,服务器方法
private void server() {
var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
StreamReader sr = new StreamReader(pipeServer);
StreamWriter sw = new StreamWriter(pipeServer);
do {
try {
pipeServer.WaitForConnection();
string test;
sw.WriteLine("Waiting");
sw.Flush();
pipeServer.WaitForPipeDrain();
test = sr.ReadLine();
Console.WriteLine(test);
}
catch (Exception ex) { throw ex; }
finally {
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
}
}

