Last active
February 16, 2022 12:30
-
-
Save adamsitnik/09bd412885383842f9ae6e47e3b39ad4 to your computer and use it in GitHub Desktop.
This file contains 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.Collections.Generic; | |
using System.IO; | |
using System.IO.Pipes; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace NamedPipes | |
{ | |
internal class Program | |
{ | |
// usage: dotnet run -c Release server $pipeName | |
// dotnet run -c Release client $pipeName | |
static async Task Main(string[] args) | |
{ | |
string pipeName = args[1]; | |
CancellationTokenSource timeout = new (TimeSpan.FromSeconds(10)); | |
if (args[0] == "server") | |
{ | |
using NamedPipeServerStream server = new (pipeName, PipeDirection.In, maxNumberOfServerInstances: 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); | |
Console.WriteLine("Server waiting for client to connect"); | |
await server.WaitForConnectionAsync(timeout.Token); | |
Console.WriteLine("Server established a connection!"); | |
using StreamReader streamReader = new StreamReader(server, Encoding.UTF8); | |
string line = null; | |
while ((line = await streamReader.ReadLineAsync()) != null) | |
{ | |
Console.WriteLine(line); | |
} | |
Console.WriteLine("EOF!"); | |
} | |
else | |
{ | |
using NamedPipeClientStream client = new (".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous); | |
Console.WriteLine("Client waiting to connect to a server"); | |
await client.ConnectAsync(timeout.Token); | |
Console.WriteLine("Client connected!"); | |
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 1 {Environment.NewLine}"), timeout.Token); | |
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 2"), timeout.Token); | |
await client.WriteAsync(Encoding.UTF8.GetBytes($" still line 2 {Environment.NewLine}"), timeout.Token); | |
await client.WriteAsync(Encoding.UTF8.GetBytes($"Line 3 {Environment.NewLine}"), timeout.Token); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment