我正在尝试学习命名管道如何工作,这样我就可以连接两个c#应用程序。
我写了两个用于测试的基本C#应用程序,但它没有用。
当我开始连接时,第一个应用程序冻结等待输入,在我从应用程序2发送输入后,它会解冻并且button1显示。但是没有任何内容出现在文本框中,为什么会出现任何想法?
应用1:
private void button1_Click(object sender, EventArgs e)
{
button1.Hide();
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe");
pipeServer.WaitForConnection();
StreamReader s = new StreamReader(pipeServer);
textBox1.Text = s.ReadToEnd();
pipeServer.Close();
button1.Show();
}
申请2:
private void button1_Click(object sender, EventArgs e)
{
NamedPipeClientStream pipeClient = new NamedPipeClientStream("testpipe");
if (pipeClient.IsConnected != true) pipeClient.Connect();
StreamWriter sw = new StreamWriter(pipeClient);
sw.WriteLine("%s", textBox1.Text);
pipeClient.Close();
}
答案 0 :(得分:0)
在NamedPipeClientStream
刷新任何数据之前,您已关闭StreamWriter
。因此,当您从服务器流中读取数据时,在连接关闭之前无法读取数据,因此您将获得一个空字符串。
您可以通过正确处理StreamWriter来解决此问题,如下所示:
private void button1_Click(object sender, EventArgs e)
{
using (var pipeClient = new NamedPipeClientStream("testpipe"))
{
if (pipeClient.IsConnected != true) pipeClient.Connect();
using (var sw = new StreamWriter(pipeClient))
{
sw.WriteLine("%s", textBox1.Text);
}
}
}
或者,您可以在AutoFlush
上将true
设置为StreamWriter
。