Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
C# Server using .NET Core Named Pipes
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
class PipeServerBinary
{
static void Main()
{
using (NamedPipeServerStream pipe = new NamedPipeServerStream("testpipe"))
{
Console.WriteLine("NamedPipeServerStream object created.");
// Wait for a client to connect
Console.Write("Waiting for client connection...");
pipe.WaitForConnection();
Console.WriteLine("Client connected.");
try
{
// Read user input and send that to the client process.
using (BinaryWriter _bw = new BinaryWriter(pipe))
using (BinaryReader _br = new BinaryReader(pipe))
{
while (true)
{
//sw.AutoFlush = true;
Console.Write("Enter text: ");
var str = Console.ReadLine();
var buf = Encoding.ASCII.GetBytes(str); // Get ASCII byte array
_bw.Write((uint)buf.Length); // Write string length
_bw.Write(buf); // Write string
Console.WriteLine("Wrote: \"{0}\"", str);
Console.WriteLine("Let's hear from the client now..");
var len = _br.ReadUInt32();
var temp = new string(_br.ReadChars((int)len));
Console.WriteLine("Received from client: {0}", temp);
}
}
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException e)
{
Console.WriteLine("ERROR: {0}", e.Message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment