private void Regenerate()
        {
            try
            {
                _pipe?.Flush();
            }
            catch
            {
                // ignored
            }

            _pipe?.Dispose();
            _pipe = new NamedPipeClientStream(".", _configuration.PipeName, PipeDirection.InOut,
                                              PipeOptions.Asynchronous);
        }
Exemple #2
0
 public void Dispose()
 {
     _streamReader?.Dispose();
     _streamWriter?.Dispose();
     _clientStream?.Close();
     _clientStream?.Dispose();
 }
 public void Dispose()
 {
     try
     {
         writer?.Dispose();
     }
     catch { }
     finally
     {
         writer = null;
     }
     try
     {
         reader?.Dispose();
     }
     catch { }
     finally
     {
         reader = null;
     }
     try
     {
         client?.Dispose();
     }
     catch { }
     finally
     {
         client = null;
     }
 }
Exemple #4
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _outClient?.Dispose();
     }
 }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         PipeStream?.Dispose();
     }
 }
Exemple #6
0
 private void ResetClient()
 {
     _stateLock.Wait();
     _state = State.Disconnecting;
     _stateLock.Release();
     try
     {
         _streamIn?.Dispose();
     }
     catch (ObjectDisposedException) { }
     _streamIn = null;
     try
     {
         _streamOut?.Dispose();
     }
     catch (ObjectDisposedException) { }
     _streamOut?.Dispose();
     _streamOut = null;
     _ss        = null;
     try
     {
         _cts?.Dispose();
     }
     catch (ObjectDisposedException) { }
     _stateLock.Wait();
     _state = State.Disconnected;
     _stateLock.Release();
 }
Exemple #7
0
        public bool SendData(string PipeName, string data, int timeout = 0)
        {
            NamedPipeClientStream namedPipeClientStream = null;

            try
            {
                namedPipeClientStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out);
                namedPipeClientStream.Connect(timeout);
                using (var streamWriter = new StreamWriter(namedPipeClientStream))
                {
                    streamWriter.Write(data);
                    streamWriter.Flush();
                }
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                namedPipeClientStream?.Dispose();
            }

            return(true);
        }
Exemple #8
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     if (disposing)
     {
         _client?.Dispose();
     }
 }
Exemple #9
0
        public void Dispose()
        {
            _client?.Dispose();
            _client = null;

            _process?.Dispose();
            _process = null;
        }
Exemple #10
0
        public void Dispose()
        {
            _client?.Dispose();
            _serverAliveCheck?.Dispose();

            _client           = null;
            _serverAliveCheck = null;
        }
Exemple #11
0
 public void Dispose()
 {
     if (IsDisposed)
     {
         return;
     }
     IsDisposed = true;
     _pipe?.Dispose();
 }
        private void DisposePipeClient()
        {
            pipeClientCTS?.Cancel();
            pipeClientCTS?.Dispose();
            pipeClientCTS = null;

            pipeClient?.Dispose();
            pipeClientCTS = null;
        }
Exemple #13
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _outClient?.Dispose();
         _socket.Send(Encoding.UTF8.GetBytes("<EOF>"));
         _socket.Shutdown(SocketShutdown.Both);
     }
 }
Exemple #14
0
#pragma warning restore 1998

        public override void Dispose()
        {
            if (!_disposedValue)
            {
                _namedPipeClientStream?.Dispose();

                _disposedValue = true;
            }
        }
        public void Dispose()
        {
            ValidateConnection();

            _clientStream?.Dispose();
            _clientStream = null;

            _reader = null;
            _writer = null;
        }
Exemple #16
0
        public void Dispose()
        {
            GC.SuppressFinalize(this);

            ClientStream?.Dispose();
            ClientStream = null;

            PipeHandle?.Dispose();
            PipeHandle = null;
        }
Exemple #17
0
        public void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }
            IsDisposed = true;

            _client?.Close();
            _client?.Dispose();
        }
Exemple #18
0
 public virtual void Dispose()
 {
     try
     {
         _stream?.Dispose();
         _rpc?.Dispose();
     }
     catch
     {
         // this shouldn't throw but it does in netcore
     }
 }
        /// <summary>
        /// Creates the pipes.
        /// </summary>
        private void CreatePipes()
        {
            _readPipe?.Dispose();
            _writePipe?.Dispose();

            // Create a read pipe for receiving notifications from server.
            _readPipe = new NamedPipeClientStream(_serverName, $"{_pipeName}client", PipeDirection.In, _options);

            // Create a write pipe for sending notifications to the server.
            _writePipe = new NamedPipeClientStream(_serverName, $"{_pipeName}server", PipeDirection.Out, _options);

            RegisterPipes(_readPipe, _writePipe);
        }
        public void Disconnect()
        {
            StopThreads();
            ClearMessageQueue();

            if (_pipe == null)
            {
                return;
            }

            _pipe?.Close();
            _pipe?.Dispose();
            _pipe = null;
            Disconnected?.Invoke(this, EventArgs.Empty);
        }
Exemple #21
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    clientRead?.Dispose();
                    clientWrite?.Dispose();
                    clientBuff = null;
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
        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.");
            }
        }
        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;
            }
        }
Exemple #24
0
        public void Start(string pipeName)
        {
            var t = Task.Run(async() =>
            {
                NamedPipeClientStream clientStream = null;
                NamedPipeServerStream serverStream = null;
                while (DoStop == false) //切断時エラーで抜けるので次の接続のために再試行
                {
                    try
                    {
                        //初期化
                        clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None); //UnityのMonoはImpersonation使えない
                        serverStream = new NamedPipeServerStream(pipeName + "receive", PipeDirection.In, 1);                                        //サーバー数1
                        try
                        {
                            clientStream.Connect(500); //UnityのMonoはAsync使えない
                        }
                        catch (TimeoutException) { }
                        if (clientStream.IsConnected == false)
                        {
                            continue;
                        }
                        serverStream.WaitForConnection(); //接続が来るまで待つ UnityのMonoはAsync使えない


                        namedPipeReceiveStream = serverStream;
                        namedPipeSendStream    = clientStream;

                        await RunningAsync();
                    }
                    finally
                    {
                        if (serverStream != null && serverStream.IsConnected)
                        {
                            serverStream.Disconnect();
                        }
                        serverStream?.Close();
                        serverStream?.Dispose();
                        clientStream?.Close();
                        clientStream?.Dispose();
                    }
                }
            });
        }
        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());
        }
Exemple #26
0
        /* Gets current logged in username and system name. This is done using a Named Pipe
         * Client that communicates with the Data Monitor process, which provides the requested
         * information.
         *
         * Param: None.
         * Return: String - current logged in user and system.
         */
        public String GetCurrentUserAndSystem()
        {
            String info;

            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "AuthInfo");

            if (pipeClient.IsConnected != true)
            {
                pipeClient.Connect();
            }

            StreamReader sr = new StreamReader(pipeClient);

            info = sr.ReadLine();
            pipeClient.Dispose();
            pipeClient.Close();

            return(info.Split(' ').First() + "@" + Environment.MachineName);
        }
Exemple #27
0
    public static async Task ConnectServer()
    {
        if (Client != null && Client.IsConnected)
        {
            try {
                await PING(false);

                return;
            }
            catch { }
        }

        bool FirstTime = Client == null;

        RunServer();
        while (true)
        {
            Thread.Sleep(1000);
            try
            {
                Client = new NamedPipeClientStream(ServerName + (ServerInstance ?? "GLOBAL"));
                Client.Connect();
                if (Client.IsConnected)
                {
                    break;
                }
            }
            catch {
                try {
                    Client?.Dispose();
                } catch { }
                continue;
            }
        }

        if (!FirstTime)
        {
            await ConnectA();
            await ConnectB();
            await SelectDriveA(DriveA.Id);
            await SelectDriveB(DriveB.Id);
        }
    }
Exemple #28
0
        public void SetAccessControl_NamedPipeStream_ClientDisposed()
        {
            string pipeName = GetUniquePipeName();
            var    server   = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            var    client   = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            Task clientConnect = client.ConnectAsync();

            server.WaitForConnection();
            clientConnect.Wait();

            // ServerStream.State = Broken, ClientStream.State = Closed
            client.Dispose();
            Assert.Throws <IOException>(() => server.Write(new byte[] { 0 }, 0, 1)); // Sets the servers PipeState to Broken
            Assert.NotNull(server.GetAccessControl());
            server.SetAccessControl(new PipeSecurity());
            Assert.Throws <ObjectDisposedException>(() => client.GetAccessControl());
            Assert.Throws <ObjectDisposedException>(() => client.SetAccessControl(new PipeSecurity()));
        }
        public async ValueTask <Stream> DialAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var pipeStream = new NamedPipeClientStream(_serverName, _pipeName, PipeDirection.InOut, _pipeOptions);
            await pipeStream.ConnectAsync(_timeoutMs, cancellationToken).ConfigureAwait(false);

            if (cancellationToken.CanBeCanceled)
            {
                cancellationToken.Register(() =>
                {
                    try
                    {
                        pipeStream.Dispose();
                    }
                    catch (Exception) { }
                }
                                           );
            }
            return(pipeStream);
        }
Exemple #30
0
        public void Publish <T>(T msg) where T : Message.Message
        {
            if (_ignoreMe.Contains(msg.MsgId))
            {
                _ignoreMe.Remove(msg.MsgId);
                return;
            }
            var client = new NamedPipeClientStream(
                ".",
                _pipeName.Write,
                PipeDirection.InOut,
                PipeOptions.None,
                System.Security.Principal.TokenImpersonationLevel.None);

            client.Connect();
            _formatter.Serialize(client, msg);
            Debug.WriteLine($"[ => ] New message of type {msg.GetType().Name} sent to pipe {_pipeName.Write}");
            client.Dispose();
        }
Exemple #31
0
        private void AsyncSend(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState;

                // End the write
                pipeStream.EndWrite(iar);
                Debug.WriteLine("[Client] Pipe successfully send data.");
                pipeStream.Flush();
                pipeStream.Close();
                pipeStream.Dispose();
            }
            catch (Exception oEX)
            {
                Debug.WriteLine(oEX.Message);
            }
        }
        public static async Task ClientDisconnectedPipeThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", PipeDirection.In))
            {
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                Task clientConnect1 = client.ConnectAsync();
                server.WaitForConnection();
                await clientConnect1;

                Assert.True(client.IsConnected);
                Assert.True(server.IsConnected);

                client.Dispose();

                Assert.Throws<IOException>(() => server.Write(buffer, 0, buffer.Length));
                Assert.Throws<IOException>(() => server.WriteByte(123));
                Assert.Throws<IOException>(() => server.Flush());
            }

            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", 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);

                client.Dispose();

                server.Read(buffer, 0, buffer.Length);
                server.ReadByte();
            }

            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("testServer2", PipeDirection.InOut))
                using (NamedPipeClientStream client = new NamedPipeClientStream("testServer2"))
                {
                    byte[] buffer = new byte[] { 0, 0, 0, 0 };

                    Task clientConnect1 = client.ConnectAsync();
                    server.WaitForConnection();
                    await clientConnect1;

                    Assert.True(client.IsConnected);
                    Assert.True(server.IsConnected);

                    client.Dispose();

                    Assert.Throws<IOException>(() => server.Write(buffer, 0, buffer.Length));
                    Assert.Throws<IOException>(() => server.WriteByte(123));
                    Assert.Throws<IOException>(() => server.Flush());
                    int length = server.Read(buffer, 0, buffer.Length);
                    Assert.Equal(0, length);
                    int byt = server.ReadByte();
                }
            }

        }
        public static async Task ClientDisconnectedPipeThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.Out))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", PipeDirection.In))
            {
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                Task clientConnect1 = client.ConnectAsync();
                server.WaitForConnection();
                await clientConnect1;

                Assert.True(client.IsConnected);
                Assert.True(server.IsConnected);

                client.Dispose();

                OtherSidePipeDisconnectWriteThrows(server);
            }

            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", 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);

                client.Dispose();

                OtherSidePipeDisconnectVerifyRead(server);
            }

            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("testServer2", PipeDirection.InOut))
                using (NamedPipeClientStream client = new NamedPipeClientStream("testServer2"))
                {
                    byte[] buffer = new byte[] { 0, 0, 0, 0 };

                    Task clientConnect1 = client.ConnectAsync();
                    server.WaitForConnection();
                    await clientConnect1;

                    Assert.True(client.IsConnected);
                    Assert.True(server.IsConnected);

                    client.Dispose();

                    OtherSidePipeDisconnectWriteThrows(server);
                    OtherSidePipeDisconnectVerifyRead(server);
                }
            }
        }
        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);
        }