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); }
private static async Task<String> IssueClientRequestAsync(String serverName, String message) { using (var pipe = new NamedPipeClientStream(serverName, "PipeName", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { pipe.Connect(); // Прежде чем задавать ReadMode, необходимо pipe.ReadMode = PipeTransmissionMode.Message; // вызвать Connect // Асинхронная отправка данных серверу Byte[] request = Encoding.UTF8.GetBytes(message); await pipe.WriteAsync(request, 0, request.Length); // Асинхронное чтение ответа сервера Byte[] response = new Byte[1000]; Int32 bytesRead = await pipe.ReadAsync(response, 0, response.Length); return Encoding.UTF8.GetString(response, 0, bytesRead); } // Закрытие канала }
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; } } }
/// <summary> /// The IsConnected property on named pipes does not detect when the client has disconnected /// if we don't attempt any new I/O after the client disconnects. We start an async I/O here /// which serves to check the pipe for disconnection. /// /// This will return true if the pipe was disconnected. /// </summary> private static async Task CreateMonitorDisconnectTask( NamedPipeClientStream pipeStream, CancellationToken cancellationToken) { // Ignore this warning because the desktop projects don't target 4.6 yet #pragma warning disable RS0007 // Avoid zero-length array allocations. var buffer = new byte[0]; #pragma warning restore RS0007 // Avoid zero-length array allocations. while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected) { // Wait a tenth of a second before trying again await Task.Delay(100, cancellationToken).ConfigureAwait(false); try { Log("Before poking pipe."); await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false); Log("After poking pipe."); } // Ignore cancellation catch (OperationCanceledException) { } catch (Exception e) { // It is okay for this call to fail. Errors will be reflected in the // IsConnected property which will be read on the next iteration of the LogException(e, "Error poking pipe"); } } }
/// <summary> /// The IsConnected property on named pipes does not detect when the client has disconnected /// if we don't attempt any new I/O after the client disconnects. We start an async I/O here /// which serves to check the pipe for disconnection. /// /// This will return true if the pipe was disconnected. /// </summary> private static async Task CreateMonitorDisconnectTask( NamedPipeClientStream pipeStream, CancellationToken cancellationToken) { var buffer = new byte[0]; while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected) { // Wait a tenth of a second before trying again await Task.Delay(100, cancellationToken).ConfigureAwait(false); try { Log("Before poking pipe."); await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false); Log("After poking pipe."); } // Ignore cancellation catch (OperationCanceledException) { } catch (Exception e) { // It is okay for this call to fail. Errors will be reflected in the // IsConnected property which will be read on the next iteration of the LogException(e, "Error poking pipe"); } } }
public static async Task ClientPInvokeChecks() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.None, 4096, 4096)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Assert.False(client.CanRead); Assert.False(client.CanSeek); Assert.False(client.CanTimeout); Assert.True(client.CanWrite); Assert.False(client.IsAsync); Assert.True(client.IsConnected); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, client.OutBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(client.OutBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => client.OutBufferSize); } Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode); Assert.NotNull(client.SafePipeHandle); Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode); client.Write(new byte[] { 123 }, 0, 1); await client.WriteAsync(new byte[] { 124 }, 0, 1); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { client.WaitForPipeDrain(); } else { Assert.Throws<PlatformNotSupportedException>(() => client.WaitForPipeDrain()); } client.Flush(); await serverTask; } } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(0, client.InBufferSize); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.True(client.InBufferSize > 0); } else { Assert.Throws<PlatformNotSupportedException>(() => client.InBufferSize); } byte[] readData = new byte[] { 0, 1 }; Assert.Equal(1, client.Read(readData, 0, 1)); Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); await serverTask; } } }
public static void ClientPInvokeChecks() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Console.WriteLine("client.CanRead = {0}", client.CanRead); Console.WriteLine("client.CanSeek = {0}", client.CanSeek); Console.WriteLine("client.CanTimeout = {0}", client.CanTimeout); Console.WriteLine("client.CanWrite = {0}", client.CanWrite); Console.WriteLine("client.IsAsync = {0}", client.IsAsync); Console.WriteLine("client.IsConnected = {0}", client.IsConnected); Console.WriteLine("client.OutBufferSize = {0}", client.OutBufferSize); Console.WriteLine("client.ReadMode = {0}", client.ReadMode); Console.WriteLine("client.SafePipeHandle = {0}", client.SafePipeHandle); Console.WriteLine("client.TransmissionMode = {0}", client.TransmissionMode); client.Write(new byte[] { 123 }, 0, 1); client.WriteAsync(new byte[] { 124 }, 0, 1).Wait(); client.WaitForPipeDrain(); client.Flush(); serverTask.Wait(); } } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Console.WriteLine("client.InBufferSize = {0}", client.InBufferSize); byte[] readData = new byte[] { 0, 1 }; client.Read(readData, 0, 1); client.ReadAsync(readData, 1, 1).Wait(); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); serverTask.Wait(); } } }