Basics of working with pipes in C# .NET part 3: message transmission

So far in the posts on pipe streams in .NET we’ve been considering the transmission of single bytes. That’s not really enough for a real-world messaging application. In this post we’ll extend our discussion to complete messages.

We have to explicitly indicate that we want to process messages in the NamedPipeServerStream constructor. Also, we’ll need to read the messages in chunks. A message is represented by a byte array and we don’t know in advance how long the message will be. Fortunately the NamedPipeServerStream object has an IsMessageComplete property which we’ll be able to use in the do-while loop:

private static void ReceiveSingleMessageFromClient()
{
	using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("test-pipe", PipeDirection.InOut, 
		1, PipeTransmissionMode.Message))
	{
		namedPipeServer.WaitForConnection();
		StringBuilder messageBuilder = new StringBuilder();
		string messageChunk = string.Empty;
		byte[] messageBuffer = new byte[5];
		do
		{
			namedPipeServer.Read(messageBuffer, 0, messageBuffer.Length);
			messageChunk = Encoding.UTF8.GetString(messageBuffer);
			messageBuilder.Append(messageChunk);
			messageBuffer = new byte[messageBuffer.Length];
		}
		while (!namedPipeServer.IsMessageComplete);

		Console.WriteLine(messageBuilder.ToString());
	}
}

The client side is much less code. You can type a message in the console which will be sent to the server as a byte array:

private static void SendSingleMessageToServer()
{
	using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
	{
		Console.Write("Enter a message to be sent to the server: ");
		string message = Console.ReadLine();
		namedPipeClient.Connect();
		byte[] messageBytes = Encoding.UTF8.GetBytes(message);
		namedPipeClient.Write(messageBytes, 0, messageBytes.Length);
	}
}

Call these methods from the client and server Main methods respectively. Start the server and client console apps separately, send a message from the client and the server’s console window should print it similar to the following:

Single message sent from client to server through pipe

Read the next part here.

View the list of posts on Messaging here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.