public async Task ConnectToNonExistentServer_Throws_TimeoutException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50)); await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test } }
public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Task clientConnectToken = client.ConnectAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token)); } }
public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - Unix implementation currently ignores timeout and cancellation token once the operation has been initiated { Task clientConnectToken = client.ConnectAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken); } ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token)); } }
public async Task PingPong_Async() { // Create names for two pipes string outName = Path.GetRandomFileName(); string inName = Path.GetRandomFileName(); // 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 (RemoteInvoke(PingPong_OtherProcess, outName, inName)) { // Wait for both pipes to be connected await Task.WhenAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process var data = new byte[1]; for (byte i = 0; i < 10; i++) { data[0] = i; await outbound.WriteAsync(data, 0, data.Length); data[0] = 0; int received = await inbound.ReadAsync(data, 0, data.Length); Assert.Equal(1, received); Assert.Equal(i, data[0]); } } }
public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException() { using (NamedPipeClientStream client = new NamedPipeClientStream("client1")) { Assert.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111)); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); }); } }
protected override ServerClientPair CreateServerClientPair() { ServerClientPair ret = new ServerClientPair(); string pipeName = GetUniquePipeName(); var writeablePipe = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); var readablePipe = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous); Task clientConnect = readablePipe.ConnectAsync(); writeablePipe.WaitForConnection(); clientConnect.Wait(); ret.readablePipe = readablePipe; ret.writeablePipe = writeablePipe; return ret; }
public async Task <TIn> RequestAsync(TOut request, int timeout, CancellationToken cancellationToken) { using (Logger.BeginScope($"{nameof(RequestAsync)}")) { using (var stream = new NamedPipeClientStream(ServerName, PipeName)) { Logger.LogInformation($"Try connect to pipe server.\r\n{ConnectionLogString}"); await stream.ConnectAsync(timeout, cancellationToken); Logger.LogDebug($"Connected to pipe server."); return(GetResponse(stream, request)); } } }
public async Task RunClient(string args) { using (var client = new NamedPipeClientStream(".", _name, PipeDirection.Out)) { await client.ConnectAsync(ClientConnectTimeoutSeconds * 1000); using (var sw = new StreamWriter(client) { AutoFlush = true }) { await sw.WriteAsync(args); } } }
public async Task Send(string message) { using (var client = new NamedPipeClientStream(Server.Id)) { using (var writer = new StreamWriter(client)) { #if NET40 client.Connect(); #else await client.ConnectAsync().ConfigureAwait(false); #endif await writer.WriteLineAsync(message).ConfigureAwait(false); } } }
public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection) { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, clientDirection)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws <ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); Assert.Throws <ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999); } }
static async Task MainAsync() { Console.WriteLine("Connecting to server..."); using (var stream = new NamedPipeClientStream(".", "StreamJsonRpcSamplePipe", PipeDirection.InOut, PipeOptions.Asynchronous)) { await stream.ConnectAsync(); Console.WriteLine("Connected. Sending request..."); var jsonRpc = JsonRpc.Attach(stream); int sum = await jsonRpc.InvokeAsync <int>("Add", 3, 5); Console.WriteLine($"3 + 5 = {sum}"); Console.WriteLine("Terminating stream..."); } }
public async void StartClient(string pipeName, string monitorSocketAddress, 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 successful to named pipe {0}", pipeName); } ConnectMonitor(monitorSocketAddress); }
public async Task DisposedClientPipe_Throws_ObjectDisposedException() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); NamedPipeClientStream pipe = pair.clientStream; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws <ObjectDisposedException>(() => pipe.Connect()); await Assert.ThrowsAsync <ObjectDisposedException>(() => pipe.ConnectAsync()); Assert.Throws <ObjectDisposedException>(() => pipe.NumberOfServerInstances); } }
protected override async Task <RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) { RpcLogger rpcLogger = new RpcLogger(_log); RpcResponseMessage rpcResponseMessage; try { var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(ConnectionTimeout); using (var pipeStream = new NamedPipeClientStream(IpcPath)) { await pipeStream.ConnectAsync(cancellationTokenSource.Token); string str = JsonConvert.SerializeObject(request, JsonSerializerSettings); byte[] bytes = Encoding.UTF8.GetBytes(str); rpcLogger.LogRequest(str); await pipeStream.WriteAsync(bytes, 0, bytes.Length, cancellationTokenSource.Token); using (MemoryStream fullResponse = await ReceiveFullResponseAsync(pipeStream, cancellationTokenSource.Token)) { fullResponse.Position = 0L; using (StreamReader streamReader = new StreamReader(fullResponse)) { using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { RpcResponseMessage responseMessage = JsonSerializer.Create(JsonSerializerSettings).Deserialize <RpcResponseMessage>(jsonTextReader); rpcLogger.LogResponse(responseMessage); rpcResponseMessage = responseMessage; } } } } } catch (TaskCanceledException ex) { var exception = new RpcClientTimeoutException($"Rpc timeout after {ConnectionTimeout.TotalMilliseconds} milliseconds", ex); rpcLogger.LogException(exception); throw exception; } catch (Exception ex) { var unknownException = new RpcClientUnknownException("Error occurred when trying to send ipc requests(s)", ex); rpcLogger.LogException(unknownException); throw unknownException; } return(rpcResponseMessage); }
private async Task RunAsync() { var host = BuildServiceHost(); var serverHandler = new StreamRpcServerHandler(host); var clientHandler = new StreamRpcClientHandler(); var client = new JsonRpcClient(clientHandler); using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { var connectTask = pipe.ConnectAsync(); hostingClient = BuildHostingClient(client); serverHandler.DefaultFeatures.Set(this); var reader = new ByLineTextMessageReader(pipe) { LeaveReaderOpen = true }; var writer = new ByLineTextMessageWriter(pipe) { LeaveWriterOpen = true }; Ambient = new SandboxAmbient(hostingClient, SandboxId); await connectTask; using (reader) using (writer) using (serverHandler.Attach(reader, writer)) using (clientHandler.Attach(reader, writer)) { // Started up hostingClient.NotifyStarted(); // Wait for disposal await disposalTcs.Task; } } // Dispose if (_ClientModule != null) { if (_ClientModule is IDisposable d) { d.Dispose(); } _ClientModule = null; } // Final cleanup. // The owner will unload appdomain so a ThreadAbortException should be thrown here. hostCallback.NotifySandboxDisposed(SandboxId); }
public async Task ConnectAsync(string pipeName) { if (_clientStream != null) { _clientStream.Close(); } _pipeName = pipeName; var clientStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); await clientStream.ConnectAsync(); clientStream.ReadMode = PipeTransmissionMode.Message; _clientStream = clientStream; RegisterForDisposal(clientStream); }
async public Task SendAsync(Event e) { Debug.WriteLine("Event sent: {0}", (object)e.name); using (var pipe = new NamedPipeClientStream(".", "NextDNS", PipeDirection.Out, PipeOptions.None)) { await pipe.ConnectAsync(1000).ConfigureAwait(false); var ms = new MemoryStream(); var ser = new DataContractJsonSerializer(typeof(Event)); ser.WriteObject(ms, e); ms.WriteByte(Convert.ToByte('\n')); byte[] json = ms.ToArray(); ms.Close(); await pipe.WriteAsync(json, 0, json.Length).ConfigureAwait(false); } }
public void SetAccessControl_NamedPipeStream() { string pipeName = GetUniquePipeName(); var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous); Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.NotNull(server.GetAccessControl()); server.SetAccessControl(new PipeSecurity()); Assert.NotNull(client.GetAccessControl()); client.SetAccessControl(new PipeSecurity()); }
protected override ServerClientPair CreateServerClientPair() { ServerClientPair ret = new ServerClientPair(); string pipeName = GetUniquePipeName(); var writeablePipe = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); var readablePipe = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous); Task clientConnect = readablePipe.ConnectAsync(); writeablePipe.WaitForConnection(); clientConnect.Wait(); ret.readablePipe = readablePipe; ret.writeablePipe = writeablePipe; return(ret); }
#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); }
public static void OSX_BufferSizeNotSupported() { int desiredBufferSize = 10; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws <PlatformNotSupportedException>(() => server.InBufferSize); Assert.Throws <PlatformNotSupportedException>(() => client.OutBufferSize); } }
public async Task <bool> ConnectAsync(int timeout) { _namedPipeClient = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); try { await _namedPipeClient.ConnectAsync(timeout); stream = _namedPipeClient; _timer.Start(); return(true); } catch (TimeoutException) { return(false); } }
public async ValueTask <Stream> ConnectAsync(SocketsHttpConnectionContext _, CancellationToken cancellationToken = default) { var namedPipe = new NamedPipeClientStream(".", endPoint, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification); try { await namedPipe.ConnectAsync(cancellationToken).ConfigureAwait(false); return(namedPipe); } catch { namedPipe.Dispose(); throw; } }
public void Subscribe(EventHandler <TResponse> value) { OnData += value; Task.Run(async() => { using NamedPipeClientStream stream = new NamedPipeClientStream(pipeName); using StreamReader reader = new StreamReader(stream); using StreamWriter writer = new StreamWriter(stream); await stream.ConnectAsync(5000, _externCancellationToken).ConfigureAwait(false); await writer.WriteLineAsync(request.ToJson()).ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); stream.WaitForPipeDrain(); while (!_externCancellationToken.IsCancellationRequested && !unsubscribeToken.IsCancellationRequested) { string responsJson = await reader.ReadLineAsync().ConfigureAwait(false); StreamlabsOBSResponse response = JsonConvert.DeserializeObject <StreamlabsOBSResponse>(responsJson); response.JsonResponse = responsJson; if (response.Results.Value <string>("_type").Equals("SUBSCRIPTION")) { OnBegin?.Invoke(this, response); } else if (response.Results.Value <string>("_type").Equals("EVENT")) { StreamlabsOBSEvent eventData = response.GetResultFirstOrDefault <StreamlabsOBSEvent>(); OnEvent?.Invoke(this, eventData); if (typeof(TResponse).IsAssignableFrom(typeof(StreamlabsOBSEvent))) { OnData?.Invoke(this, eventData as TResponse); } else { OnData?.Invoke(this, eventData.GetDataFirstOrDefault <TResponse>()); } } else { OnUnsupported?.Invoke(this, responsJson); } } }, _externCancellationToken); }
public override async Task ConnectAsync(TimeSpan timeout = default) { timeout = timeout == default ? Timeout.InfiniteTimeSpan : timeout; _logger?.LogDebug($"Connecting to pipe '{_pipeName}' with timeout '{timeout}'."); var stream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, _tokenImpersonationLevel); _channel = new NamedPipeTransportChannel(this, stream); await stream.ConnectAsync((int)timeout.TotalMilliseconds); _logger?.LogDebug($"Connected to pipe '{_pipeName}'. Starting message loop."); RegisterMessageCallback(_channel, HandleReceivedData, false); RunReaderLoop(_channel, () => OnDisconnected(new ChannelConnectedEventArgs <NamedPipeTransportChannel>(_channel))); _logger?.LogDebug($"Message loop running."); }
protected override async Task <StreamPair> CreateConnectedStreamsAsync() { string name = FileSystemTest.GetNamedPipeServerStreamName(); var server = new NamedPipeServerStream(name, PipeDirection.In); var client = new NamedPipeClientStream(".", name, PipeDirection.Out); await WhenAllOrAnyFailed(server.WaitForConnectionAsync(), client.ConnectAsync()); var fs1 = new FileStream(new SafeFileHandle(server.SafePipeHandle.DangerousGetHandle(), true), FileAccess.Read); var fs2 = new FileStream(new SafeFileHandle(client.SafePipeHandle.DangerousGetHandle(), true), FileAccess.Write); server.SafePipeHandle.SetHandleAsInvalid(); client.SafePipeHandle.SetHandleAsInvalid(); return(fs1, fs2); }
public async Task CreateConnection(string pipeName) { Logger?.LogDebug($"Attempting to connect to: {pipeName}"); try { client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous); //await client.ConnectAsync(30000); await client.ConnectAsync(30000).ConfigureAwait(false); stream = new StreamWriter(client); Logger?.LogDebug($"Connection established to: {pipeName}"); } catch (Exception exception) { Logger?.LogError(exception.Message); } }
public async Task InitializeCodeSearchServiceAsync() { if (_jsonRpc != null) { return; } string clientPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "AzDevOpsInteractiveClient.exe"); string pipeName = $"AzDevOpsClientPipe-{Process.GetCurrentProcess().Id}"; _clientProcess = new Process(); _clientProcess.StartInfo = new ProcessStartInfo(clientPath) { Arguments = $@"--RootDir ""{_repoInfo.RootDir}"" " + $@"--ProjectUri {_repoInfo.ProjectUri} " + $@"--ProjectName ""{_repoInfo.ProjectName}"" " + $@"--RepoName ""{_repoInfo.RepoName}"" " + $@"--RpcPipeName ""{pipeName}"" ", UseShellExecute = false, CreateNoWindow = true, }; _logger.LogDebug($"FastCodeNav: Launching {clientPath} with arguments '{_clientProcess.StartInfo.Arguments}'"); if (!_clientProcess.Start()) { _logger.LogError($"FastCodeNav: Failed to launch {clientPath}"); return; } _logger.LogDebug($"FastCodeNav: Connecting to search service client with PID {_clientProcess.Id}"); var stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await stream.ConnectAsync(); _logger.LogDebug($"FastCodeNav: Connected to search service client."); var jsonRpc = new JsonRpc(stream); var jsonRpcProxy = jsonRpc.Attach <ICodeSearchService>(); jsonRpc.StartListening(); _jsonRpc = jsonRpc; _logger.LogDebug($"FastCodeNav: Issuing a warmup RPC request"); _jsonRpc.InvokeAsync("WarmUpAsync").FireAndForget(_logger); }
protected override async Task <IDuplexPipe> ConnectPipelineAsync(int sendMaxMessageSize, int receiveMaxMessageSize, CancellationToken cancellationToken) { // TODO: The URL should be parsed in RpConnectionInfo constructor . // If invalid an ArgumentException should be thrown there. if (this.ConnectionInfo.HostUrl is Uri url) { #pragma warning disable CA2000 // Dispose objects before losing scope string pipeName = PipeUri.LookupPipeName(url); if (string.IsNullOrEmpty(pipeName)) { throw new RpcCommunicationException(RpcCommunicationStatus.Unavailable, $"Failed to connect to named pipe at '{url}'"); } NamedPipeClientStream?pipeClientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous); try { await pipeClientStream.ConnectAsync(cancellationToken).ContextFree(); var sendOptions = new System.IO.Pipelines.PipeOptions( pauseWriterThreshold: sendMaxMessageSize * 2, resumeWriterThreshold: sendMaxMessageSize, readerScheduler: System.IO.Pipelines.PipeScheduler.Inline, useSynchronizationContext: false); var receiveOptions = new System.IO.Pipelines.PipeOptions( pauseWriterThreshold: receiveMaxMessageSize * 2, resumeWriterThreshold: receiveMaxMessageSize, readerScheduler: System.IO.Pipelines.PipeScheduler.Inline, useSynchronizationContext: false); var connection = new StreamDuplexPipe(pipeClientStream); //, sendOptions, receiveOptions); pipeClientStream = null; // Prevent disposal return(connection); } finally { pipeClientStream?.Dispose(); } #pragma warning restore CA2000 // Dispose objects before losing scope } else { throw new InvalidOperationException("Missing connection URL."); } }
private async Task Connect(ApiClient <T> oldApi = null) { pipe = new NamedPipeClientStream(ServerName, PipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await pipe.ConnectAsync(cancellationToken.Token); if (cancellationToken.IsCancellationRequested) { return; } client = new ApiClient <T>(pipe, pipe, oldApi); client.Disconnected += Client_Disconnected; if (oldApi == null) { SetupApi?.Invoke(client.Api); } client.Start(); }
public async Task Connect(TimeSpan timeout) { var stream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); try { await stream.ConnectAsync((int)timeout.TotalMilliseconds).ConfigureAwait(false); } catch { stream.Dispose(); throw; } _stream = stream; _rpc = JsonRpc.Attach(stream, this); }
private static async Task RunAsync(string[] args, CancellationToken token, ManualResetEvent mre) { try { using (var pipeStream = new NamedPipeClientStream(".", Constants.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await pipeStream.ConnectAsync(token).ConfigureAwait(true); Console.WriteLine("Connected to server; writing args."); using (var reader = new StreamReader(pipeStream)) using (var writer = new StreamWriter(pipeStream)) { writer.WriteLine("Client Args (ProcessId = {0}):", System.Diagnostics.Process.GetCurrentProcess().Id); for (var i = 0; i < args.Length; i++) { var arg = args[i]; writer.WriteLine("\targs[{0}] = {1}", i, arg); } writer.WriteLine(); await writer.FlushAsync().ConfigureAwait(true); Console.WriteLine("Reading full arg set."); while (!reader.EndOfStream) { var line = reader.ReadLine(); if (line == string.Empty) { break; } Console.WriteLine(line); } } } } finally { mre.Set(); } }
public override async Task <Kernel> CreateKernelAsync(NamedPipeConnectionOptions options, KernelInvocationContext context) { var clientStream = new NamedPipeClientStream( ".", options.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); await clientStream.ConnectAsync(); clientStream.ReadMode = PipeTransmissionMode.Message; var proxyKernel = CreateProxyKernel(options, clientStream); return(proxyKernel); }
private static void 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); } } }
public static async Task ServerDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer3", PipeDirection.Out)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); Assert.Throws <IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws <IOException>(() => client.WriteByte(123)); Assert.Throws <IOException>(() => client.Flush()); } if (Interop.IsWindows) // Unix implementation of InOut doesn't fail on server.Write/Read when client disconnects due to allowing for additional connections { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.InOut)) using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); Assert.Throws <IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws <IOException>(() => client.WriteByte(123)); Assert.Throws <IOException>(() => client.Flush()); int length = client.Read(buffer, 0, buffer.Length); Assert.Equal(0, length); int byt = client.ReadByte(); } } }
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; }
public async Task <Stream> GetBidirectionalStreamAsync(CancellationToken token) { NamedPipeClientStream pipeStream = null; try { pipeStream = new NamedPipeClientStream(_serverName, _pipeName, PipeDirection.InOut, _pipeOptions); await pipeStream.ConnectAsync(_timeoutMs, token).ConfigureAwait(false); return(pipeStream); } catch (Exception ex) { Log.Error(ex, "There was a problem connecting to the named pipe"); pipeStream?.Dispose(); throw; } }
public void GetAccessControl_NamedPipeServerStream_Broken() { string pipeName = GetUniquePipeName(); var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous); Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.NotNull(server.GetAccessControl()); server.SetAccessControl(new PipeSecurity()); Assert.NotNull(client.GetAccessControl()); client.SetAccessControl(new PipeSecurity()); client.Dispose(); Assert.Throws<IOException>(() => server.Write(new byte[] { 0 }, 0, 1)); // Sets the servers PipeState to Broken server.SetAccessControl(new PipeSecurity()); }
public void PingPong_Sync() { // Create names for two pipes string outName = Path.GetRandomFileName(); string inName = Path.GetRandomFileName(); // 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 (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 ClientTryConnectedThrows() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - Unix implementation currently ignores timeout and cancellation token once the operation has been initiated { Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50)); await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); Task clientConnectToken = client.ConnectAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken); } ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token)); } }
public static void OSX_BufferSizeNotSupported() { int desiredBufferSize = 10; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize); Assert.Throws<PlatformNotSupportedException>(() => client.OutBufferSize); } }
public void Unix_MultipleServerDisposal_DoesntDeletePipe() { // Test for when multiple servers are created and linked to the same FIFO. The original ServerStream // that created the FIFO is disposed. The other servers should still be valid and useable. string serverName = GetUniquePipeName(); var server1 = new NamedPipeServerStream(serverName, PipeDirection.In); // Creates the FIFO var server2 = new NamedPipeServerStream(serverName, PipeDirection.In); var client1 = new NamedPipeClientStream(".", serverName, PipeDirection.Out); var client2 = new NamedPipeClientStream(".", serverName, PipeDirection.Out); Task server1Task = server1.WaitForConnectionAsync(); // Opens a handle to the FIFO Task server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO as server1 Task client1Task = client1.ConnectAsync(); Task.WaitAll(server1Task, server2Task, client1Task); // client1 connects to server1 AND server2 Assert.True(server1.IsConnected); Assert.True(server2.IsConnected); // Get rid of client1/server1 and make sure server2 isn't connected (so that it can connect to client2) server1.Dispose(); client1.Dispose(); server2.Disconnect(); Assert.False(server2.IsConnected); server2Task = server2.WaitForConnectionAsync(); // Opens a handle to the same FIFO Task client2Task = client2.ConnectAsync(); Task.WaitAll(server2Task, client2Task); // Should not block! Assert.True(server2.IsConnected); }
public static void ClientUnsupportedOperationThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("unique4", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "unique4", PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); ConnectedPipeUnsupportedOperationThrows(client); } }
public static async Task ClientAllReadyConnectedThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer1", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer1", PipeDirection.InOut, PipeOptions.Asynchronous)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); Assert.Throws<InvalidOperationException>(() => client.Connect()); var ctx = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - the cancellation token is ignored after the operation is initiated, due to base Stream's implementation { Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientReadToken); } ctx.Cancel(); Assert.True(client.ReadAsync(buffer, 0, buffer.Length, ctx.Token).IsCanceled); var ctx1 = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // [ActiveIssue(812, PlatformID.AnyUnix)] - the cancellation token is ignored after the operation is initiated, due to base Stream's implementation { Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); } ctx1.Cancel(); Assert.True(server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } }
public static async Task ServerDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer3", PipeDirection.Out)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(123)); Assert.Throws<IOException>(() => client.Flush()); } if (Interop.IsWindows) // Unix implementation of InOut doesn't fail on server.Write/Read when client disconnects due to allowing for additional connections { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.InOut)) using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(123)); Assert.Throws<IOException>(() => client.Flush()); int length = client.Read(buffer, 0, buffer.Length); Assert.Equal(0, length); int byt = client.ReadByte(); } } }
public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection) { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, clientDirection)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999); } }
public static async Task ServerDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer3", PipeDirection.Out)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); OtherSidePipeDisconnectWriteThrows(client); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // Unix implementation of InOut doesn't fail on server.Write/Read when client disconnects due to allowing for additional connections { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.InOut)) using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); OtherSidePipeDisconnectWriteThrows(client); OtherSidePipeDisconnectVerifyRead(client); } } }
public static async Task ServerAfterDisconnectThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("unique3", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "unique3", PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); await clientConnect; Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); server.Disconnect(); Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // double disconnect AfterDisconnectWriteOnlyPipeThrows(server); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // on Unix, InOut doesn't result in the same Disconnect-based errors due to allowing for other connections { using (NamedPipeServerStream server = new NamedPipeServerStream("unique3", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (NamedPipeClientStream client = new NamedPipeClientStream("unique3")) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); await clientConnect; Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); server.Disconnect(); Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // double disconnect AfterDisconnectReadWritePipeThrows(server); } } }
public static void ClientConnectTimeoutThrows() { using (NamedPipeClientStream client = new NamedPipeClientStream("client1")) { Assert.Throws<ArgumentOutOfRangeException>(() => client.Connect(-111)); Assert.Throws<ArgumentOutOfRangeException>(() => NotReachable(client.ConnectAsync(-111))); } }
[PlatformSpecific(PlatformID.Windows)] // Unix doesn't currently support message mode public void Windows_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte); client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte); server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } }
public static void Unix_BufferSizeRoundtripping(PipeDirection direction) { int desiredBufferSize = 0; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); desiredBufferSize = server.OutBufferSize * 2; } using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); if ((direction & PipeDirection.Out) != 0) { Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue); } if ((direction & PipeDirection.In) != 0) { Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue); } } }
public void Unix_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); client.ReadMode = PipeTransmissionMode.Byte; server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } }
public static void Windows_BufferSizeRoundtripping() { int desiredBufferSize = 10; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.OutBufferSize); Assert.Equal(desiredBufferSize, client.InBufferSize); } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.InBufferSize); Assert.Equal(0, client.OutBufferSize); } }
public static void ServerReadOnlyThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("unique3", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "unique3", PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); ConnectedPipeReadOnlyThrows(server); } }