Julian
Julian

Reputation: 427

Why does this simple async NamedPipe connection not work?

I need a way to let my Windows Service communicate with my Windows Client and for that I would like to use NamedPipes. So I just created a very simple Client/Server scenario but I just can't figure out why it isn't working. The program freezes when I am calling writer.AutoFlush = true.

Server code:

var server = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
Console.WriteLine("Waiting for client connection...");

await server.WaitForConnectionAsync();
Console.WriteLine("Client connected.");

using var reader = new StreamReader(server, Encoding.UTF8);
await using var writer = new StreamWriter(server, Encoding.UTF8);
writer.AutoFlush = true;

while (true)
{
    var message = await reader.ReadLineAsync();
    Console.WriteLine($"Received: {message}");
    await writer.WriteLineAsync($"Echo: {message}");
}

Client code:

await using var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut, PipeOptions.Asynchronous);
Console.WriteLine("Connecting to server...");

await client.ConnectAsync();
Console.WriteLine("Connected to server.");

using var reader = new StreamReader(client, Encoding.UTF8);
Console.WriteLine("Reader initialized.");

await using var writer = new StreamWriter(client, Encoding.UTF8);
writer.AutoFlush = true;
Console.WriteLine("Writer initialized.");

await writer.WriteLineAsync("Hello, server!");
Console.WriteLine("Message sent.");

var response = await reader.ReadLineAsync();
Console.WriteLine($"Server response: {response}");

Server output:

Waiting for client connection...
Client connected.

Client output:

Connecting to server...
Connected to server.
Reader initialized.

Is anyone able to spot the mistake?

Upvotes: 1

Views: 68

Answers (1)

Julian
Julian

Reputation: 427

Okay after hours of trial and error I now finally know the problem. It seems as you aren't allowed to specify the encoding in the stream object (at least at the server). So i just removed the Encoding.UTF8 in the StreamReader and StreamWriter and now it works!

final server code:

var server = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
Console.WriteLine("Waiting for client connection...");

await server.WaitForConnectionAsync();
Console.WriteLine("Client connected.");

using var reader = new StreamReader(server);
await using var writer = new StreamWriter(server);
writer.AutoFlush = true;

while (true)
{
    var message = await reader.ReadLineAsync();
    Console.WriteLine($"Received: {message}");
    await writer.WriteLineAsync($"Echo: {message}");
}

Upvotes: 2

Related Questions