FrozenHeart
FrozenHeart

Reputation: 20746

How to use named pipes in C# correctly -- several connections, server recreation etc

I need to implement an inter-process communication between C# applications. I decided to use named pipes and wrote the following code:

Server

while (true)
{
    using (var server = new NamedPipeServerStream("some_pipe"))
    {
        server.WaitForConnection();
        using (var reader = new StreamReader(server))
        {
            string line = reader.ReadLine();
            MessageBox.Show(line);
        }
    }
}

Client

using (var client = new NamedPipeClientStream("some_pipe"))
{
    client.Connect();

    using (var writer = new StreamWriter(client))
    {
        writer.AutoFlush = true;
        writer.WriteLine(path);
        client.WaitForPipeDrain();
    }
}

I have the following questions about it:

Upvotes: 19

Views: 23459

Answers (2)

Andrew Arnott
Andrew Arnott

Reputation: 81801

Here is a sample that creates a named pipe server that listens to n client connections concurrently.

It essentially listens for one incoming client connection at a time, and as soon as the connection is made, it starts listening for the next one (using a new NamedPipeServerStream object) while still exchanging messages with the prior one(s).

Upvotes: 2

Fidel Orozco
Fidel Orozco

Reputation: 1056

This will not work. Multiple clients connecting to just one NamedPipeServerStream is a feature not available. Its name with "...ServerStream" is misleading. Pipes are 1 to 1 connections. You must have multiple server instances serving the same pipe for many clients. This Code Project shows how to implement a Server Pipes and may help you.

Upvotes: 13

Related Questions