コード例 #1
0
        private static async Task ListenCoreAsync(
            string pipeName,
            AsyncQueue <ListenResult> queue,
            Func <string> getClientLoggingIdentifier,
            CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                NamedPipeServerStream?pipeStream = null;

                try
                {
                    // Create the pipe and begin waiting for a connection. This
                    // doesn't block, but could fail in certain circumstances, such
                    // as Windows refusing to create the pipe for some reason
                    // (out of handles?), or the pipe was disconnected before we
                    // starting listening
                    CompilerServerLogger.Log($"Constructing pipe and waiting for connections '{pipeName}'");
                    pipeStream = NamedPipeUtil.CreateServer(pipeName);

                    // The WaitForConnectionAsync API does not fully respect the provided CancellationToken
                    // on all platforms:
                    //
                    //  https://github.com/dotnet/runtime/issues/40289
                    //
                    // To mitigate this we need to setup a cancellation Task and dispose the NamedPipeServerStream
                    // if it ever completes. Once all of the NamedPipeServerStream for the given pipe name are
                    // disposed they will all exit the WaitForConnectionAsync method
                    var connectTask = pipeStream.WaitForConnectionAsync(cancellationToken);
                    if (!PlatformInformation.IsWindows)
                    {
                        var cancelTask    = Task.Delay(TimeSpan.FromMilliseconds(-1), cancellationToken);
                        var completedTask = await Task.WhenAny(new[] { connectTask, cancelTask }).ConfigureAwait(false);

                        if (completedTask == cancelTask)
                        {
                            throw new OperationCanceledException();
                        }
                    }

                    await connectTask.ConfigureAwait(false);

                    CompilerServerLogger.Log("Pipe connection established.");
                    var connection = new NamedPipeClientConnection(pipeStream, getClientLoggingIdentifier());
                    queue.Enqueue(new ListenResult(connection: connection));
                }
                catch (OperationCanceledException)
                {
                    // Expected when the host is shutting down.
                    CompilerServerLogger.Log($"Pipe connection cancelled");
                    pipeStream?.Dispose();
                }
                catch (Exception ex)
                {
                    CompilerServerLogger.LogException(ex, $"Pipe connection error");
                    queue.Enqueue(new ListenResult(exception: ex));
                    pipeStream?.Dispose();
                }
            }
        }
コード例 #2
0
ファイル: SingleInstance.cs プロジェクト: dotsetup/dotsetup
        /// <summary>
        ///     The function called when a client connects to the named pipe. Note: This method is called on a non-UI thread.
        /// </summary>
        /// <param name="iAsyncResult"></param>
        private void NamedPipeServerConnectionCallback(IAsyncResult iAsyncResult)
        {
            try
            {
                // End waiting for the connection
                _namedPipeServerStream.EndWaitForConnection(iAsyncResult);

                // Could not create handle - server probably not running
                if (!_namedPipeServerStream.IsConnected)
                {
                    return;
                }

                // Read data and prevent access to _namedPipeXmlPayload during threaded operations
                lock (_namedPiperServerThreadLock)
                {
                    // Read data from client
                    StreamReader reader = new StreamReader(_namedPipeServerStream);
                    while (!reader.EndOfStream)
                    {
                        string namedPipeServerData = reader.ReadLine();
                        // raise event
                        OnPipeCmdEvent?.Invoke(new PipeCmdEventArgs(namedPipeServerData));
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // EndWaitForConnection will exception when someone closes the pipe before connection made
                // In that case we dont create any more pipes and just return
                // This will happen when app is closing and our pipe is closed/disposed
                return;
            }
#if DEBUG
            catch (Exception e)
#else
            catch (Exception)
#endif
            {
#if DEBUG
                Logger.GetLogger().Error("Exception caught on single instance pipe server's listener: " + e.Message);
#endif
            }
            finally
            {
                // Close the original pipe (we will create a new one each time)
                _namedPipeServerStream.Dispose();
            }

            // Create a new pipe for next connection
            NamedPipeServerCreateServer();
        }
コード例 #3
0
ファイル: ApiServer.cs プロジェクト: victor0225/NeuralAction
        public void Stop()
        {
            if (IsStarted)
            {
                isOpened  = false;
                IsStarted = false;
                cancel.Cancel();
                server.Wait();

                pipe.Dispose();
                pipe = null;
            }
        }
コード例 #4
0
 static async Task HandleConnection(NamedPipeServerStream stream)
 {
     try {
         var handler = new CodeLensConnectionHandler();
         var rpc     = JsonRpc.Attach(stream, handler);
         handler.rpc = rpc;
         await rpc.Completion;
         handler.Dispose();
         stream.Dispose();
     } catch (Exception ex) {
         LogVS(ex);
     }
 }
コード例 #5
0
ファイル: Serial.cs プロジェクト: zrbruce/FlingOS
        /// <summary>
        /// Cleanly disconnects the pipe and terminates reading.
        /// </summary>
        /// <returns>True if disconnected successfully.</returns>
        public bool Disconnect()
        {
            bool OK = true;

            if (ThePipe != null)
            {
                ThePipe.Close();
                ThePipe.Dispose();
                ThePipe = null;
            }

            return(OK);
        }
コード例 #6
0
        public void Dispose()
        {
            try
            {
                if (_pipeServer.IsConnected)
                {
                    _pipeServer.Disconnect();
                }
            }
            catch { }

            _pipeServer.Dispose();
        }
コード例 #7
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            _lastFrameTask?.Wait();
            _lastAudio?.Wait();

            _ffmpegIn.Dispose();

            _audioPipe?.Dispose();

            _ffmpegProcess.WaitForExit();

            _videoBuffer = null;
        }
コード例 #8
0
        public static void ServerWhenDisplosedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("unique2", PipeDirection.InOut))
            {
                server.Dispose();

                Assert.Throws <ObjectDisposedException>(() => server.Disconnect());        // disconnect when disposed
                Assert.Throws <ObjectDisposedException>(() => server.WaitForConnection()); // disconnect when disposed
                Assert.Throws <ObjectDisposedException>(() => server.WriteByte(5));
                Assert.Throws <ObjectDisposedException>(() => server.ReadByte());
                Assert.Throws <ObjectDisposedException>(() => server.IsMessageComplete);
            }
        }
コード例 #9
0
        public override void Dispose()
        {
            base.Dispose();
            lock (_lock)
            {
                if (_pipeServer.IsConnected)
                {
                    _pipeServer.Disconnect();
                }

                _pipeServer.Dispose();
            }
        }
コード例 #10
0
        public async Task DisposedServerPipe_Throws_ObjectDisposedException()
        {
            using (NamedPipePair pair = CreateNamedPipePair())
            {
                NamedPipeServerStream pipe = pair.serverStream;
                pipe.Dispose();
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                Assert.Throws <ObjectDisposedException>(() => pipe.Disconnect());
                Assert.Throws <ObjectDisposedException>(() => pipe.WaitForConnection());
                await Assert.ThrowsAsync <ObjectDisposedException>(() => pipe.WaitForConnectionAsync());
            }
        }
コード例 #11
0
ファイル: ElevationProxyMain.cs プロジェクト: caoxk/coapp
 private void DisposeStreams()
 {
     if (_fromClientPipe != null)
     {
         _fromClientPipe.Dispose();
         _fromClientPipe = null;
     }
     if (_toServerPipe != null)
     {
         _toServerPipe.Dispose();
         _toServerPipe = null;
     }
 }
コード例 #12
0
        public void Dispose()
        {
            if (_debugAdapter.Protocol?.IsRunning == true)
            {
                // Cleanly close down debugging
                _debugAdapter.SendTerminateAndExit();
                _debugAdapter.Protocol.Stop(2000);
                _debugAdapter.Protocol.WaitForReader();
            }

            _pipeServer.Disconnect();
            _pipeServer.Dispose();
        }
コード例 #13
0
 public void Dispose()
 {
     if (_server != null)
     {
         _exit = true;
         Thread.Sleep(20);
         if (_server.IsConnected)
         {
             _server.Disconnect();
         }
         _server.Dispose();
     }
 }
コード例 #14
0
 public void CloseConnections()
 {
     IsRunning = false;
     try
     {
         NamedPipeStream_Server.Dispose();
         NamedPipeStream_Server.Close();
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString());
     }
 }
コード例 #15
0
ファイル: WorkerWrapper.cs プロジェクト: samisalamiws/warp
        public void Dispose()
        {
            if (IsAlive)
            {
                IsAlive = false;

                SendCommand(new NamedSerializableObject("Exit"));

                StreamSend.Dispose();
                StreamReceive.Dispose();
                StreamHeartbeat.Dispose();
            }
        }
コード例 #16
0
        public async void SendMessage(string message)
        {
            try
            {
                await _writer.WriteLineAsync(message);

                _writer.Flush();
                _server.WaitForPipeDrain();

                if (message == "Server Over")
                {
                    _server.Close();
                    _server.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(ConnectedUserName + " Disconnected");
                _server.Close();
                _server.Dispose();
            }
        }
コード例 #17
0
        public void PipeReader()
        {
            // Open the named pipe.
            var server = new NamedPipeServerStream("Data");

            //Console.WriteLine("Waiting for connection...");
            server.WaitForConnection();

            //Console.WriteLine("Connected.");
            var br = new BinaryReader(server);

            //var bw = new BinaryWriter(server);

            while (true)
            {
                try
                {
                    var len = (int)br.ReadUInt32();            // Read string length
                    if (len == 0)
                    {
                        continue;
                    }
                    var      str     = new string(br.ReadChars(len)); // Read string
                    string[] clients = str.Split(';');
                    this._names     = new List <string>();
                    this._dataArray = new List <string[]>();
                    for (int i = 0; i < clients.Length; i++)
                    {
                        string name = clients[i].Split('%')[0];
                        this._names.Add(name);
                        string[] dates = (clients[i].Split('%')[1]).Split(',');
                        this._dataArray.Add(dates);
                    }

                    dele invokeDELE = new dele(this.updateDataGrid);
                    this.Invoke(invokeDELE);



                    //Console.WriteLine("Read: " + str);
                }
                catch (EndOfStreamException)
                {
                    break;                    // When client disconnects
                }
            }

            MessageBox.Show("Engine has disconnected");
            server.Close();
            server.Dispose();
        }
コード例 #18
0
        private void Worker(NamedPipeServerStream m_Server)
        {
            try
            {
                m_Log.Warn($">> Worker");
                do
                {
                    try
                    {
                        if (m_Server == null)
                        {
                            m_Server = new NamedPipeServerStream(m_PipeName, PipeDirection.In, 1, PipeTransmissionMode.Message);
                        }
                        m_Log.Warn($">> Waiting for Connection");
                        m_Server.WaitForConnection();
                        m_Log.Warn($"<< Waiting for Connection");
                        int readCount;
                        do
                        {
                            m_Log.Warn($">> Read Stream");
                            byte[] seBuffer = new byte[1024];
                            readCount = m_Server.Read(seBuffer, 0, seBuffer.Length);
                            string clientMessage = Encoding.UTF8.GetString(seBuffer, 0, readCount);
                            m_Log.Debug($"** Client message completed?{m_Server.IsMessageComplete} {readCount} long -> {clientMessage}#");
                            var clientData = JsonSerializer.DeserializeFromString <T>(clientMessage);
                            m_Log.Debug($"** Client data: {clientData}");
                            if (readCount > 0 && !object.Equals(clientData, default(T)))
                            {
                                OnClientMessageReceived(clientData);
                            }
                        } while (!m_Server.IsMessageComplete && readCount > 0);

                        m_Server.Dispose();
                        m_Server = null;
                    }
                    catch (Exception ex)
                    {
                        m_Log.Warn($"** Exception {ex}");
                        m_ToRun = false;
                    }
                } while (m_ToRun);
            }
            catch (Exception ex)
            {
                m_Log.Warn($"** Worker abort exception {ex}");
            }
            finally
            {
                m_Log.Warn($"<< Worker");
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Y56380X/GpioService
        private static void Main()
        {
            // Build pipe server
            var ipcServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1);

            // TODO: TEST
            new Thread(TestClient)
            {
                IsBackground = true
            }.Start();

            // Start pipe server
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                if (!ipcServer.IsConnected)
                {
                    ipcServer.WaitForConnection();
                }

                var request  = ipcServer.ReadMessage <GpioRequest>();
                var response = new GpioResponse();

                using (new UserContext(ipcServer.GetImpersonationUserName()))
                {
                                        #if DEBUG
                    Console.WriteLine(JsonConvert.SerializeObject(request));
                                        #endif

                    var gpioManager = new GpioManager();                     // TODO: Get from DI
                    switch (request.Action)
                    {
                    case RequestAction.Export:
                        response.Result  = gpioManager.TryExport(request.PinNumber, out IGpioPin pin);
                        response.Payload = (pin as GpioPin)?.Path;
                        break;

                    case RequestAction.Unexport:
                        response.Result = gpioManager.TryUnexport(new GpioPin(request.PinNumber));
                        break;

                    default:
                        response.Result = false;
                        break;
                    }
                }

                ipcServer.Disconnect();
            }

            ipcServer.Dispose();
        }
コード例 #20
0
        public void Read_ReturnsZeroLength_WhenClosedDuringRead()
        {
            var tasks       = new List <Task>();
            var pipeName    = Guid.NewGuid().ToString();
            var readStream  = new NamedPipeServerStream(pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.WriteThrough | PipeOptions.Asynchronous);
            var writeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.WriteThrough | PipeOptions.Asynchronous);

            try
            {
                var reader = new NamedPipeTransport(readStream);
                var writer = new NamedPipeTransport(writeStream);

                var waiter = new TaskCompletionSource <string>();

                tasks.Add(Task.Run(
                              async() =>
                {
                    _output.WriteLine("Before WaitForConnectAsync");
                    await readStream.WaitForConnectionAsync().ConfigureAwait(false);
                    _output.WriteLine("After WaitForConnectAsync");

                    Task.WaitAll(Task.Run(() => waiter.SetResult("go")));
                    var readBuffer = new byte[100];
                    var length     = await reader.ReceiveAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false);

                    Assert.Equal(0, length);
                }));

                tasks.Add(Task.Run(
                              async() =>
                {
                    _output.WriteLine("Before ConnectAsync");
                    await writeStream.ConnectAsync(500).ConfigureAwait(false);
                    _output.WriteLine("After ConnectAsync");

                    var r = await waiter.Task.ConfigureAwait(false);

                    writer.Close();

                    _output.WriteLine("After Close");
                }));

                Task.WaitAll(tasks.ToArray());
            }
            finally
            {
                readStream.Disconnect();
                readStream.Dispose();
                writeStream.Dispose();
            }
        }
コード例 #21
0
ファイル: PluginSystem.cs プロジェクト: h3zjp/NowplayingTunes
        void PipeThread()
        {
            NamedPipeServerStream pipeServer = null;

            try
            {
                pipeServer = new NamedPipeServerStream("NowPlayingTunes", PipeDirection.InOut);
                StreamString stream = new StreamString(pipeServer);
                pipeServer.WaitForConnection();
                //When Connected
                if (Song.getLatestSong() != null)
                {
                    String           TweetText  = getTweetText();
                    Core.iTunesClass latestsong = Song.getLatestSong();
                    String           sendtext   = Core.Replace.ReplaceText(TweetText, latestsong);
                    stream.WriteString(sendtext);
                }
                pipeServer.Close();
                pipeServer.Dispose();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[PluginSystem] ERROR");
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                    {
                        pipeServer.Dispose();
                    }
                }
            }
            //Remake thread
            StartThread();
        }
コード例 #22
0
ファイル: SlaveManager.cs プロジェクト: Reaxt/RhythmThing
 public void CloseWindow()
 {
     if (pipe.IsConnected)
     {
         _writer.AutoFlush = true;
         _writer.WriteAsync("close");
         pipe.Disconnect();
         pipe.Dispose();
         _accessor.Dispose();
         mappedFile.Dispose();
         _aliveWindows.Remove(this);
         this.Alive = false;
     }
 }
コード例 #23
0
 private static async Task WaitForConnectionAsync(
     NamedPipeServerStream pipeServerStream,
     CancellationToken cancellationToken)
 {
     try
     {
         await pipeServerStream.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
     }
     catch
     {
         pipeServerStream.Dispose();
         throw;
     }
 }
コード例 #24
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    process.Dispose();
                    server.Close();
                    server.Dispose();
                }

                disposedValue = true;
            }
        }
コード例 #25
0
        public void Stop()
        {
            if (pipeServer != null && pipeServer.IsConnected)
            {
                pipeServer.Disconnect();
                pipeServer.Dispose();
            }

            if (renderAppProcess != null && !renderAppProcess.HasExited)
            {
                renderAppProcess.Kill();
                renderAppProcess = null;
            }
        }
コード例 #26
0
 public void Dispose()
 {
     if (_disposed)
     {
         return;
     }
     _disposed = true;
     if (_stream.IsConnected)
     {
         _stream.Disconnect();
     }
     _stream.Close();
     _stream.Dispose();
 }
コード例 #27
0
        private void KillStream()
        {
            if (stream != null)
            {
                try
                {
                    stream.Close();
                    stream.Dispose();
                }
                catch (Exception) { }
            }

            stream = null;
        }
コード例 #28
0
        public void ProcessCommands()
        {
            _server.WaitForConnection();
            var completed = false;

            while (!completed)
            {
                var msg = _pipeChanell.GetMessage();
                completed = ProcessCommand(msg);
                _pipeChanell.SendAck(_lastError, _lastErrorMessage);
            }

            _server.Dispose();
        }
コード例 #29
0
        private void StartPipeServerThread(object obj)
        {
            var param = obj as PipeServerThreadParameter;

            var server = new NamedPipeServerStream(
                _name,
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Message,
                PipeOptions.Asynchronous);

            try
            {
                while (true)
                {
                    _log.Debug("Pipe server ({id}) waiting for connection", param.Id);

                    server.WaitForConnectionAsync(CancellationToken).GetAwaiter().GetResult();

                    var ss      = new StreamString(server);
                    var request = ss.ReadString();

                    var response = ExecuteCommand(request);

                    ss.WriteString(response);
                    server.WaitForPipeDrain();
                    server.Disconnect();
                }
            }
            catch (OperationCanceledException)
            {
                _log.Debug("Pipe server ({id}) shutting down", param.Id);
            }
            catch (Exception ex)
            {
                _log.Error(ex, "Pipe server ({id}) error: {message}", param.Id, ex.Message);

                if (param.Semaphore != null)
                {
                    param.Semaphore.Release();
                }
            }
            finally
            {
                server.Close();
                server.Dispose();
            }

            _log.Verbose("Pipe server ({id}) thread terminating", param.Id);
        }
コード例 #30
0
        /// <summary>
        /// This does the actual work of changing the status and shutting down any threads we may have for
        /// disconnection.
        /// </summary>
        private void InternalDisconnect()
        {
            ErrorUtilities.VerifyThrow(_packetPump.ManagedThreadId != Thread.CurrentThread.ManagedThreadId, "Can't join on the same thread.");
            _terminatePacketPump.Set();
            _packetPump.Join();
#if CLR2COMPATIBILITY
            _terminatePacketPump.Close();
#else
            _terminatePacketPump.Dispose();
#endif
            _pipeServer.Dispose();
            _packetPump = null;
            ChangeLinkStatus(LinkStatus.Inactive);
        }
コード例 #31
0
        public void GetAccessControl_NamedPipeClientStream_Broken()
        {
            string pipeName = GetUniquePipeName();
            var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, 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());

            server.Dispose();
            Assert.Throws<IOException>(() => client.Write(new byte[] { 0 }, 0, 1)); // Sets the clients PipeState to Broken
            Assert.Throws<InvalidOperationException>(() => client.SetAccessControl(new PipeSecurity()));
        }
コード例 #32
0
        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();
                }
            }

        }
コード例 #33
0
        public static void ServerWhenDisplosedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("unique2", PipeDirection.InOut))
            {
                server.Dispose();

                Assert.Throws<ObjectDisposedException>(() => server.Disconnect());  // disconnect when disposed
                Assert.Throws<ObjectDisposedException>(() => server.WaitForConnection());  // disconnect when disposed
                WhenDisposedPipeThrows(server);
            }
        }
コード例 #34
0
        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);
                }
            }
        }
コード例 #35
0
        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);
        }
コード例 #36
0
 public static void Windows_CreateFromDisposedServerHandle_Throws_ObjectDisposedException(PipeDirection direction)
 {
     // The pipe is closed when we try to make a new Stream with it
     var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
     SafePipeHandle handle = pipe.SafePipeHandle;
     pipe.Dispose();
     Assert.Throws<ObjectDisposedException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle).Dispose());
 }
コード例 #37
0
 public static void Windows_CreateFromAlreadyBoundHandle_Throws_ArgumentException(PipeDirection direction)
 {
     // The pipe is already bound
     var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
     Assert.Throws<ArgumentException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle));
     pipe.Dispose();
 }