Skip to content

Instantly share code, notes, and snippets.

@sean-gilliam
Created November 20, 2014 20:04
Show Gist options
  • Save sean-gilliam/0e29f78164aca6908872 to your computer and use it in GitHub Desktop.
Save sean-gilliam/0e29f78164aca6908872 to your computer and use it in GitHub Desktop.
Named Pipes Example
namespace Pipes
{
using System;
using System.Linq;
using System.IO;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static byte[] ReadMessage(PipeStream s)
{
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[0x1000]; // Read in 4KB blocks
do { ms.Write(buffer, 0, s.Read(buffer, 0, buffer.Length)); }
while (!s.IsMessageComplete);
return ms.ToArray();
}
public static void Main(string[] args)
{
var src = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
var pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(
new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow)
);
pipeSecurity.AddAccessRule(
new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow)
);
while (true)
{
if (src.IsCancellationRequested)
break;
using (var s = new NamedPipeServerStream("test", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
{
Console.WriteLine("[Server] Pipe created {0}", s.GetHashCode());
s.WaitForConnection();
byte[] msg = Encoding.UTF8.GetBytes("Hello");
s.Write(msg, 0, msg.Length);
Console.WriteLine("[Server] " + Encoding.UTF8.GetString(ReadMessage(s)));
}
}
}, src.Token);
Enumerable.Range(0, 9000).Select(x => new Task(() =>
{
using (var s = new NamedPipeClientStream(".", "test", PipeDirection.InOut))
{
s.Connect();
s.ReadMode = PipeTransmissionMode.Message;
Console.WriteLine("[Client] " + Encoding.UTF8.GetString(ReadMessage(s)));
var msg = Encoding.UTF8.GetBytes("Hello right back " + x);
s.Write(msg, 0, msg.Length);
}
})).ToList().ForEach(x => x.Start());
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment