Skip to content

Instantly share code, notes, and snippets.

@klkucan
Created March 15, 2018 15:27
Show Gist options
  • Save klkucan/b76c85c77fdfcde51aa4eeb1c6f7cd0b to your computer and use it in GitHub Desktop.
Save klkucan/b76c85c77fdfcde51aa4eeb1c6f7cd0b to your computer and use it in GitHub Desktop.
Pipe in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
namespace PIPE_Client
{
class Program
{
static void Main(string[] args)
{
Decoder decoder = Encoding.UTF8.GetDecoder();
Byte[] bytes = new Byte[10];
Char[] chars = new Char[10];
// TB?: named pipe
using (NamedPipeClientStream pipeStream =
new NamedPipeClientStream("messagepipe"))
{
pipeStream.Connect();
pipeStream.ReadMode = PipeTransmissionMode.Message;
int numBytes;
do
{
string message = "";
do
{
// TB?: is it a block function?
numBytes = pipeStream.Read(bytes, 0, bytes.Length);
int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0);
message += new String(chars, 0, numChars);
} while (!pipeStream.IsMessageComplete);
decoder.Reset();
Console.WriteLine(message);
System.Threading.Thread.Sleep(500);
} while (numBytes != 0);
Console.ReadKey();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
namespace PIPE_Sample
{
class Program
{
static void Main(string[] args)
{
UTF8Encoding encoding = new UTF8Encoding();
string message1 = "Named Pipe Message Example.";
string message2 = "Another Named Pipe Message Example.";
Byte[] bytes;
int nMsgCnt = 0;
using (NamedPipeServerStream pipeStream = new
NamedPipeServerStream("messagepipe",
PipeDirection.InOut, 1,
PipeTransmissionMode.Message,
PipeOptions.None))
{
Console.WriteLine("Pipe server waiting for connection ... ...");
pipeStream.WaitForConnection();
// Let’s send two messages.
Console.WriteLine("Pipe server sending message {0}: {1}", nMsgCnt, message1);
bytes = encoding.GetBytes(message1);
pipeStream.Write(bytes, 0, bytes.Length);
nMsgCnt++;
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Pipe server sending message {0}: {1}", nMsgCnt, message2);
bytes = encoding.GetBytes(message2);
pipeStream.Write(bytes, 0, bytes.Length);
}
Console.ReadKey();
}
}
}
@nohwnd
Copy link

nohwnd commented Mar 17, 2021

Thanks, just what I needed. It's surprisingly difficult to find a good example of sending multiple messages in a row.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment