private void NamedPipeIpcClient_Closed(object sender, EventArgs e) { NamedPipeIpcClient s = (NamedPipeIpcClient)sender; lock (_syncRootClients) { if (_clients.ContainsKey(s.Id)) { OnClientClosed(s); _clients.Remove(s.Id); } else { _pendingClients.Remove(s.Id); } } s.Dispose(); }
private void OnClientConnected(NamedPipeIpcClient val) { ClientConnected?.Invoke(this, new ClientEventArgs(val)); }
private async void CreatePipeAsync(string id, PipeDirection direction, CancellationToken token) { try { if (direction == PipeDirection.InOut) { throw new ArgumentException("InOut is not a valid value. Use In OR Out!"); } id = direction == PipeDirection.In ? $"i_{id}" : $"o_{id}"; NamedPipeServerStream pipeServer = new NamedPipeServerStream( direction == PipeDirection.In ? Settings.ServerInputPipeName : Settings.ServerOutputPipeName, PipeDirection.InOut, _maxConnections); Trace.TraceInformation($"Server {id} waiting for connection ..."); SemaphoreSlim semaphore = direction == PipeDirection.In ? _semaphoreStartInputConnections : _semaphoreStartOutputConnections; await semaphore.WaitAsync(token); try { await pipeServer.WaitForConnectionAsync(token); } catch (Exception e) { Trace.TraceError("Error waiting for pipe connection: {0}", e.Message); pipeServer.Dispose(); return; } finally { semaphore.Release(); } Trace.TraceInformation($"Client connected on id: {id}"); try { StreamString ss = new StreamString(pipeServer, null); string clientId = await ss.ReadStringAsync(token); lock (_syncRootClients) { if (_pendingClients.TryGetValue(clientId, out NamedPipeIpcClient val)) { if (direction == PipeDirection.In) { if (val.InputPipe == null) { val.InputPipe = pipeServer; } else { Trace.TraceWarning( $"Client {val.Id} tried to register two input pipes, closing ..."); } } else { if (val.OutputPipe == null) { val.OutputPipe = pipeServer; } else { Trace.TraceWarning( $"Client {val.Id} tried to register two output pipes, closing ..."); } } if (val.InputPipe != null && val.OutputPipe != null) { Trace.TraceInformation($"Client {val.Id} successfully connected two pipes."); _clients.Add(val.Id, val); _pendingClients.Remove(val.Id); OnClientConnected(val); } else { pipeServer.Close(); pipeServer.Dispose(); } } else { Trace.TraceInformation($"Client {clientId} registered on {id}"); NamedPipeIpcClient npic = new NamedPipeIpcClient(clientId); if (direction == PipeDirection.In) { npic.InputPipe = pipeServer; } else { npic.OutputPipe = pipeServer; } npic.Closed += NamedPipeIpcClient_Closed; _pendingClients.Add(clientId, npic); } } } catch (IOException e) { Trace.TraceError(e.Message); } catch (ArgumentException) { Trace.TraceInformation($"Client disconnected before he sent an Id on connection {id}."); pipeServer.Dispose(); } } catch (Exception ex) { Util.TraceException("Error creating pipe", ex); OnError(ex); } }