Forked from abgoswam/csharpserver_dotnet_namedpipe.cs
Created
April 22, 2020 09:54
-
-
Save jrgcubano/d7b1766d3e94c5bd9bea57855395232b to your computer and use it in GitHub Desktop.
C# Server using .NET Core Named Pipes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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