Monday, June 22, 2009

An easy way to communicate between two processes in .net

In order to communicate between two processes, we uses named pipes. Named pipes provide one-way or duplex pipes for communication between a pipe server and one or more pipe clients. Named pipes can be used for inter process communication locally or over network. Any process can act as either a named piped server or client or both.

Let’s see an example where a string value will be shared between two processes. .NET framework 3.5 has released a new class for creating named pipes server. The name of the class is NamedPipeServerStream. After creating the named pipes server, it will wait for a client process to connect to it. There is a new class NamedPipeClientStream in .NET framework3.5 which is used for creating the named pipes client. Let’s create the named pipes server:

//create the server instance
NamedPipeServerStream server = new NamedPipeServerStream("SetuInstance", PipeDirection.InOut);
//the following code snippet make the server always in a listening mode.
while (true)
{
server.WaitForConnection();
using (StreamReader reader = new StreamReader(server))
{
string stringValue = reader.ReadLine();
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Invoker)delegate
{
MessageBox.Show(stringValue);
});
}
server = new NamedPipeServerStream("SetuInstance", ipeDirection.InOut);
}

As you can see in the above code snippet, after creating the named pipes server, it waits for the client connection. As soon as it connects to the named pipe client, it reads the string value.

Now, let’s create the named pipes client:

using (NamedPipeClientStream client = new NamedPipeClientStream(".", "SetuInstance", PipeDirection.InOut))
{
try
{
//try to connect to IPC Server
client.Connect(500);
//write data to the pipe so that IPC server can get the string.
using (StreamWriter writer = new StreamWriter(client))
{
writer.WriteLine("An easy way to communicate between two processes!");
}
}
catch
{

}
}

In the above code snippet, you can see, how easily you can pass string to named pipes server.

NamedPipeClientStream and NamedPipeServerStream are very helpful class added in .NET framework 3.5. Now the processes can easily communicate between each others.

Hope this help!

1 comment:

Ahasan Habib said...

I created one to one chat application using namedpipe protocol with the help of your blog entry. Thanks for your nice post.