Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Source 

Pipe server,communication between different processes using pipes

I was adding extension handling to my application, so I wrote this piece of code to allow inter-process communication (IPC) between different applications or instances of the same application allowing dynamic interaction and passing of data.I hope you will benefit from it

Code
public class NamedPipeServer : IDisposable
    {
        private string pipeName;
        private NamedPipeServerStream pipeServer;
        private CancellationTokenSource cancellationTokenSource;
        private bool isDisposed;

        public event EventHandler<string[]> ArgumentsReceived;

        public NamedPipeServer(string pipeName)
        {
            if (string.IsNullOrEmpty(pipeName))
                throw new ArgumentException("Pipe name cannot be null or empty.");

            this.pipeName = pipeName;
        }

        public async Task Start()
        {            
            if (pipeServer != null && pipeServer.IsConnected)
                throw new InvalidOperationException("The server is already running.");

            cancellationTokenSource = new CancellationTokenSource();
            pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            await pipeServer.WaitForConnectionAsync(cancellationTokenSource.Token);
            _ = Task.Run(() => HandleIncomingMessages(cancellationTokenSource.Token));
        }

        public void Stop()
        {
            cancellationTokenSource?.Cancel();
            pipeServer?.Dispose();
        }        

        private async Task HandleIncomingMessages(CancellationToken cancellationToken)
        {
            using (StreamReader reader = new StreamReader(pipeServer))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        string data = await reader.ReadLineAsync();
                        if (!string.IsNullOrEmpty(data))
                        {
                            string[] arguments = data.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                            ArgumentsReceived?.Invoke(this, arguments);
                        }
                    }
                    catch (IOException ex)
                    {
                        Console.WriteLine($"Pipe server error: {ex.Message}");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error: {ex.Message}");
                    }
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    Stop();
                    cancellationTokenSource?.Dispose();
                }

                isDisposed = true;
            }
        }
    }

If you have suggestions for improving the code I'm open minded.
I wish you all the best.
the only thing you could really add to that IMO is to add specific functions for the arguments received if you are trying to create a c2c server.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Delphi] by Redacted KaosMar 8, 2022 01:05 AM 2 192 Mar 8, 2022 01:05 AM
Last Post: Hs32-Idir
by this_site_sucksJun 19, 2019 01:43 AM 5 220 Jun 19, 2019 01:43 AM
Last Post: GetASyncKeyState()
[Delphi] by gz_hackMar 8, 2019 08:45 PM 8 556 Mar 8, 2019 08:45 PM
Last Post: gz_hack