Basics of working with pipes in C# .NET part 4: basic conversation with messages

In this post we saw how a pipe stream client and server can send each other single bytes. In this post we managed to send a single message from the client to the server. It’s time to marry the two concepts. We’ll let the client and server start a conversation.

The server side code has nothing new compared to the posts referred to above:

private static void ConversationWithTheClient()
{
	using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("test-pipe", PipeDirection.InOut,
		1, PipeTransmissionMode.Message))
	{
		Console.WriteLine("Server waiting for a connection...");
		namedPipeServer.WaitForConnection();
		Console.Write("A client has connected, send a greeting from the server: ");
		string message = Console.ReadLine();
		byte[] messageBytes = Encoding.UTF8.GetBytes(message);
		namedPipeServer.Write(messageBytes, 0, messageBytes.Length);

		string response = ProcessSingleReceivedMessage(namedPipeServer);
		Console.WriteLine("The client has responded: {0}", response);
		while (response != "x")
		{
			Console.Write("Send a response from the server: ");
			message = Console.ReadLine();
			messageBytes = Encoding.UTF8.GetBytes(message);
			namedPipeServer.Write(messageBytes, 0, messageBytes.Length);
			response = ProcessSingleReceivedMessage(namedPipeServer);
			Console.WriteLine("The client is saying {0}", response);
		}

		Console.WriteLine("The client has ended the conversation.");
	}
}

private static string ProcessSingleReceivedMessage(NamedPipeServerStream namedPipeServer)
{
	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);
	return messageBuilder.ToString();
}

Call ConversationWithTheClient from Main in the server console app. The client side code has a couple of new features:

private static void ConversationWithTheServer()
{
	using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(".", "test-pipe", PipeDirection.InOut))
	{
		namedPipeClient.Connect();
		Console.WriteLine("Client connected to the named pipe server. Waiting for server to send the first message...");
		namedPipeClient.ReadMode = PipeTransmissionMode.Message;
		string messageFromServer = ProcessSingleReceivedMessage(namedPipeClient);
		Console.WriteLine("The server is saying {0}", messageFromServer);
		Console.Write("Write a response: ");
		string response = Console.ReadLine();
		byte[] responseBytes = Encoding.UTF8.GetBytes(response);
		namedPipeClient.Write(responseBytes, 0, responseBytes.Length);
		while (response != "x")
		{
			messageFromServer = ProcessSingleReceivedMessage(namedPipeClient);
			Console.WriteLine("The server is saying {0}", messageFromServer);
			Console.Write("Write a response: ");
			response = Console.ReadLine();
			responseBytes = Encoding.UTF8.GetBytes(response);
			namedPipeClient.Write(responseBytes, 0, responseBytes.Length);
		}
	}
}

private static string ProcessSingleReceivedMessage(NamedPipeClientStream namedPipeClient)
{
	StringBuilder messageBuilder = new StringBuilder();
	string messageChunk = string.Empty;
	byte[] messageBuffer = new byte[5];
	do
	{
		namedPipeClient.Read(messageBuffer, 0, messageBuffer.Length);
		messageChunk = Encoding.UTF8.GetString(messageBuffer);
		messageBuilder.Append(messageChunk);
		messageBuffer = new byte[messageBuffer.Length];
	}
	while (!namedPipeClient.IsMessageComplete);
	return messageBuilder.ToString();
}

The “.” in the constructor indicates the local machine. There’s no NamedPipeClientStream constructor where you can only set the pipe name and the pipe direction. The pipe transmission mode can be set after the NamedPipeClientStream has been constructed using the ReadMode property.

Call ConversationWithTheServer from Main of the client console application. Run both apps and you can start a simple conversation like this:

Pipe stream simple conversation

Read the next part here.

View the list of posts on Messaging here.

Advertisements

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

One Response to Basics of working with pipes in C# .NET part 4: basic conversation with messages

  1. Michal says:

    thanks a lot, finally easy to understand explanation of how named pipes works

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: