您好,我的 NamedPipeServer 上有一个错误。
如果我使用单个流 WriteLine,服务器和客户端工作正常 并冲洗。
在我尝试写入新行后,出现错误 IOException Pipe Broken。
服务器管道
NamedPipeServerStream 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);
if (test.Contains("Mouse"))
{
Invoke((Action)delegate
{
listBox1.Items.Add(test);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
});
}
if (test.Contains("Bt1"))
{
Invoke((Action)delegate
{
listBox2.Items.Add("BT");
});
}
}
catch (Exception ex) { throw ex; }
finally
{
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
客户端管道
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".",
"testpipe", PipeDirection.InOut, PipeOptions.None);
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
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
{
//First Write Working!
sw.WriteLine("Mouse Pos: " + e.Location);
sw.Flush();
//Second Write i get Exception and Pipe Broken
sw.WriteLine("Bt1:1");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
}
如何解决这个问题?
最佳答案
您的服务器在收到第一行后关闭连接。因此,当发送第二行时,管道已经关闭(或“损坏”)。
您应该在服务器端创建一个内部循环并添加一些命令来关闭 conn
NamedPipeServerStream 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();
// start inner loop
while(pipeServer.IsConnected)
{
test = sr.ReadLine();
Console.WriteLine(test);
if (test.Contains("Mouse"))
{
Invoke((Action)delegate
{
listBox1.Items.Add(test);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
});
}
if (test.Contains("Bt1"))
{
Invoke((Action)delegate
{
listBox2.Items.Add("BT");
});
}
// close command
if (test == "Close")
pipeServer.Disconnect();
}
}
catch (Exception ex) { throw ex; }
finally
{
//If i remove this line, The code Work
//pipeServer.WaitForPipeDrain();
//if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
请注意,这并不是一个真正好的设计,但可能适合您的测试目的。您可能应该将连接客户端的处理封装到自己的方法甚至类中。
并注意 catch(Exception ex) { throw ex; }
有点无用(除非您想要摆脱原始的堆栈跟踪)。
关于C# NamedPipeServer 新写入后损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42073517/