Communication using Named Pipes (.NET)

Introduction

Named Pipes are a mechanism for instant messaging between processes.

Following diagram shows a simple communication setup using Named Pipes:

  • The Server open a named pipe.
  • A client can listen to that pipe.
  • The client will receive message in real-time, the server send to the pipe.
  • The client must know the name of the pipe to connect to it.
  • Pipes are Byte-stream oriented.

A pipe is only useable for two processes. If you’ve a server and multiple clients, you’ll need different pipes for each client-server connection.

They also support full duplex communication and data transfer between local processes and between different machines on a network (Anonymous pipes are limited to processes which are running on the same PC). They also support client impersonation, which enables connecting processes to use their own set of permissions on remote servers.

Demo 1

A service send message via a named pipe to a client (console application) which writes it to console.

To start with I’ve created a VS solution with following projects:

  • WorkerServiceServer (the server Part of the demo – a worker application)
  • SimpleClient (the client part of demo – a console application)

You can download the source code from this git repository.

Server Implementation

Here is a very basic implementation of the server:

following is the code for the Demo1 function:

Output

Here is the output of running the server code

At this point server is started and waiting for client connection.

Client Implementation

Following is a basic implementation of the client:

Client / Server Communication

Now, if we run both projects together, we will get the following output

As we can see that server is started and client can connect to it. Then server or client can send message and a basic message flow is shown in the above diagram.

Demo 2

For this example, the code is available in the repo. Here I’ve created a library project and define the following PipeServer class which encapsulates pipe and setup StreamReader to send text-data. You can check the code in the repository

Now, I used the WorkerServiceServer project to use the above shown PipeServer:

and here is the Client part

Output Demo2

Here you can see that Server sent a text message which is received by the client using named pipes:

Summary

In this post, we saw how Named Pipes provides us an easy way to implement Interprocess communication. They are part of the Base Class Library (BCL) in .NET.

For more information and examples, please check the Microsoft documentation on this link.

Let me know if you have some questions or comments. Till next time, Happy Learning.


Discover more from Hex Quote

Subscribe to get the latest posts sent to your email.

Discover more from Hex Quote

Subscribe now to keep reading and get access to the full archive.

Continue reading