public async void StartClient(string pipeName, CancellationToken cancellationToken) { if (pipeName != null && !_configured) { Trace.Info("Connecting to named pipe {0}", pipeName); _outClient = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous); await _outClient.ConnectAsync(cancellationToken); _writeStream = new StreamWriter(_outClient, Encoding.UTF8); _configured = true; Trace.Info("Connection successfull to named pipe {0}", pipeName); } }
// Asynchronously create a new connection public async Task<Tuple<Int32, string>> ConnectAsync(string endpoint) { // Parse the endpoint. It should be formatted as // "\\server\pipe\name". string [] components = endpoint.Split(new char[] { '\\' }); if (components.Length != 5) { return Tuple.Create(-1, "invalid endpoint format"); } // Create the connection // NOTE: It is essential that the PipeOptions.Asynchronous option be // specified, or the ReadAsync and WriteAsync methods will block // (and I don't mean they'll call await and halt - I mean they'll // never return a Task object) var connection = new NamedPipeClientStream( components[2], components[4], PipeDirection.InOut, PipeOptions.Asynchronous ); // Try to connect asynchronously try { await connection.ConnectAsync(); } catch (Exception e) { return Tuple.Create(-1, e.Message); } // Store the connection Int32 connectionId = -1; lock (this) { // Compute the next connection id. Watch for overflow, because // we use -1 as the invalid identifier. if (_nextConnectionId < 0) { connection.Close(); return Tuple.Create(-1, "connection ids exhausted"); } connectionId = _nextConnectionId++; // Do the storage _connections[connectionId] = connection; } // All done return Tuple.Create(connectionId, ""); }
private async Task<UserProfileResultMock> CreateProfileClientTestWorkerAsync(string input, CancellationToken ct = default(CancellationToken)) { string jsonResp = null; using (NamedPipeClientStream client = new NamedPipeClientStream("Microsoft.R.Host.UserProfile.Creator{b101cc2d-156e-472e-8d98-b9d999a93c7a}")) { await client.ConnectAsync(ct); byte[] data = Encoding.Unicode.GetBytes(input); await client.WriteAsync(data, 0, data.Length, ct); await client.FlushAsync(ct); byte[] responseRaw = new byte[1024]; var bytesRead = await client.ReadAsync(responseRaw, 0, responseRaw.Length, ct); jsonResp = Encoding.Unicode.GetString(responseRaw, 0, bytesRead); } return Json.DeserializeObject<UserProfileResultMock>(jsonResp); }
#pragma warning disable 1998 // Because in the NET451 code path, there's nothing to await public override async Task<Stream> Open(string address) { _namedPipeClientStream = new NamedPipeClientStream( ".", address, PipeDirection.InOut, PipeOptions.Asynchronous); #if NET451 _namedPipeClientStream.Connect(); #else await _namedPipeClientStream.ConnectAsync().ConfigureAwait(false); #endif return _namedPipeClientStream; }
private static int PingPong_OtherProcess(string inName, string outName) { // Create pipes with the supplied names using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) { // Wait for the connections to be established Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync()); // Repeatedly read then write bytes from and to the other process for (int i = 0; i < 10; i++) { int b = inbound.ReadByte(); outbound.WriteByte((byte)b); } } return SuccessExitCode; }
private async Task<RUserProfileServiceResponse> ProfileWorkerAsync(string name, string log, RUserProfileServiceRequest request, CancellationToken ct) { using (NamedPipeClientStream client = new NamedPipeClientStream(name)) { try { await client.ConnectAsync(ct); string jsonReq = JsonConvert.SerializeObject(request); byte[] data = Encoding.Unicode.GetBytes(jsonReq.ToString()); await client.WriteAsync(data, 0, data.Length, ct); await client.FlushAsync(ct); byte[] responseRaw = new byte[1024]; var bytesRead = await client.ReadAsync(responseRaw, 0, responseRaw.Length, ct); string jsonResp = Encoding.Unicode.GetString(responseRaw, 0, bytesRead); return Json.DeserializeObject<RUserProfileServiceResponse>(jsonResp); } catch (Exception ex) when (!ex.IsCriticalException()) { _logger.LogError(log, request.Username); return RUserProfileServiceResponse.Blank; } } }
public void PingPong() { // Create names for two pipes string outName = Guid.NewGuid().ToString("N"); string inName = Guid.NewGuid().ToString("N"); // Create the two named pipes, one for each direction, then create // another process with which to communicate using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (var remote = RemoteInvoke(PingPong_OtherProcess, outName, inName)) { // Wait for both pipes to be connected Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process for (byte i = 0; i < 10; i++) { outbound.WriteByte(i); int received = inbound.ReadByte(); Assert.Equal(i, received); } } }
public static async Task ClientCloneTests() { const string pipeName = "fooClientclone"; byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received0 = new byte[] { }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte)) using (NamedPipeClientStream clientBase = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None)) { await Task.WhenAll(server.WaitForConnectionAsync(), clientBase.ConnectAsync()); using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.Out, false, true, clientBase.SafePipeHandle)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(1, client.NumberOfServerInstances); } Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode); Task clientTask = Task.Run(() => client.Write(msg1, 0, msg1.Length)); int len1 = server.Read(received1, 0, msg1.Length); await clientTask; Assert.Equal(msg1.Length, len1); Assert.Equal(msg1, received1); // test special cases of buffer lengths = 0 int len0 = server.Read(received0, 0, 0); Assert.Equal(0, len0); Assert.Equal(0, await server.ReadAsync(received0, 0, 0)); } } }
public static async Task ClientServerOneWayOperations( string pipeName, PipeDirection serverDirection, bool asyncServerPipe, bool asyncClientPipe, bool asyncServerOps, bool asyncClientOps) { PipeDirection clientDirection = serverDirection == PipeDirection.Out ? PipeDirection.In : PipeDirection.Out; PipeOptions serverOptions = asyncServerPipe ? PipeOptions.Asynchronous : PipeOptions.None; PipeOptions clientOptions = asyncClientPipe ? PipeOptions.Asynchronous : PipeOptions.None; using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, serverOptions)) { byte[] received = new byte[] { 0 }; Task clientTask = Task.Run(async () => { using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, clientDirection, clientOptions)) { if (asyncClientOps) { await client.ConnectAsync(); if (clientDirection == PipeDirection.In) { received = await ReadBytesAsync(client, sendBytes.Length); } else { await WriteBytesAsync(client, sendBytes); } } else { client.Connect(); if (clientDirection == PipeDirection.In) { received = ReadBytes(client, sendBytes.Length); } else { WriteBytes(client, sendBytes); } } } }); if (asyncServerOps) { await server.WaitForConnectionAsync(); if (serverDirection == PipeDirection.Out) { await WriteBytesAsync(server, sendBytes); } else { received = await ReadBytesAsync(server, sendBytes.Length); } } else { server.WaitForConnection(); if (serverDirection == PipeDirection.Out) { WriteBytes(server, sendBytes); } else { received = ReadBytes(server, sendBytes.Length); } } await clientTask; Assert.Equal(sendBytes, received); server.Disconnect(); Assert.False(server.IsConnected); } }
internal static async Task<BuildResponse> Send(string pipeName, BuildRequest request) { using (var client = new NamedPipeClientStream(pipeName)) { await client.ConnectAsync(); await request.WriteAsync(client); return await BuildResponse.ReadAsync(client); } }