Pipe broken exception when attempting to send multiple messages from client to server in C#

44 views Asked by At

I have decided to implement a really cool program where a Windows Forms Application is the client and it sends login details to a server which is a Console program listening for messages from clients continuously. I have a dictionary variable on the console program and it contains a list of registered users. When I send a sample string like "David", if that string exists in that dictionary then no exception is thrown and I can repeat the send operation and no Pipe Broken Exception is thrown until I change the input message to something that does not exist in the dictionary, help me fix this so that I can change the input from the end of the client whether the key exists in my dictionary or not its printed out on the console window. I have attached the server code and the client code, Thank You.

Server Code

static async Task HandleClient()
{
    using (var serverStream = new NamedPipeServerStream("ServerProgram", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
    {
        try
        {
            await serverStream.WaitForConnectionAsync();
            using (var reader = new StreamReader(serverStream, Encoding.UTF8, true, 4096, true))
            using (var writer = new StreamWriter(serverStream, Encoding.UTF8, 4096, true))
            {
                string message = await reader.ReadLineAsync();
                if (message == null)
                {
                    // Client closed the connection
                    Console.WriteLine("Client closed the connection");
                    return;
                }

                Console.WriteLine(message);

                var userAndPassword = message.Split('-');
                if (userAndPassword.Length == 2)
                {
                    var user = userAndPassword[0];
                    var pass = userAndPassword[1];

                    if (dataBase.ContainsKey(user))
                    {
                        Console.WriteLine(user + " found");
                    }
                    else
                    {
                        await writer.WriteLineAsync("user does not exist");
                        await writer.FlushAsync();
                    }
                }
                else
                {
                    // Invalid message format
                    Console.WriteLine("Invalid message format");
                }
            }
        }
        catch (IOException ex) when ((ex.InnerException as System.Net.Sockets.SocketException)?.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset)
        {
            // Client disconnected abruptly
            Console.WriteLine("Client disconnected abruptly");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}
 //declare a dictionary that can be used to store the details of three customers
 static Dictionary<string, string> dataBase = new Dictionary<string, string>(); 
 static async Task Main(string[] args)
 {
     //programatically register the details of three customers
     dataBase.Add("Timothy", "789633");
     dataBase.Add("David", "670544");
     dataBase.Add("Mary", "765444");
     //output to the user the server program has started
     Console.WriteLine("Server program started....");
     Console.WriteLine("Server started on " + DateTime.Now);
     Console.WriteLine("Listening for incoming connections...");
     //use an infinite while loop to listen for messages from clients
     while (true)
     {
         await Task.Run(() => HandleClient());
     }
  }

Client Code

  //use a pipe server stream to send the ip and account number to the server
  using(var pipeServer = new NamedPipeClientStream(".","ServerProgram",PipeDirection.InOut))
  {
      Console.WriteLine("Connecting to the server");
      pipeServer.Connect();
      Console.WriteLine("Connected to server");
      //send the ip and the account name to the server
      var writer = new StreamWriter(pipeServer);
      writer.Write(string.Join("-", new string[] { ip, pass }));
      writer.Flush(); 
  }

Why does the server code thrown an exception for a broken pipe when I change the input string on the client side and how can I fix this?

0

There are 0 answers