你好我的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; }
}
}
如何解决这个问题?
答案 0 :(得分:2)
收到第一行后,您的服务器关闭连接。因此,当发送第二行时,管道已经关闭(或者#34;损坏")。
您应该在服务器端创建一个内部循环并添加一些命令来关闭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; }
有点无用(除非你希望摆脱原始的堆栈跟踪)。