Basics of working with pipes in C# .NET part 3: message transmission
June 19, 2015 Leave a comment
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:
Read the next part here.
View the list of posts on Messaging here.