class Program
{
static async Task Main(string[] args)
{
using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
{
Console.WriteLine("Connecting to service...");
await client.ConnectAsync();
using (StreamWriter writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true })
using (StreamReader reader = new StreamReader(client, Encoding.UTF8))
{
while (true)
{
Console.Write("Type Message: ");
string message = Console.ReadLine();
await writer.WriteLineAsync(message);
string response = await reader.ReadLineAsync();
Console.WriteLine($"[ANSWER]: {response}");
}
}
}
}
}
要查看实际发生的事情,您需要通过调试器同时运行服务器和客户端。
如果管道的另一端在等待时断开连接,它将返回null。 因此,服务器在客户端断开之后崩溃。 另外,服务器处置
ReadLineAsync()
可能会丢失错误(试图将其缓冲区冲洗到封闭管道上)。添加了这两种情况的一些错误处理,服务器应运行更长的时间。