最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to reconnect to NamedPipeServerStream - Stack Overflow

programmeradmin8浏览0评论

I am making Windows service in C#, and I need to communicate with this service using NamedPipeServerStream. When I start this service, connecting to it is without any problem. When I close the client and reopen it, I cannot reconnect to this service. Where is the problem?

Here is server code:

private async Task StartPipeServer()
 {
     while (true)
     {
         PipeSecurity pipeSecurity = new PipeSecurity();
         pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
         using (var pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, pipeSecurity))
         {
             await pipeServer.WaitForConnectionAsync();
             using (StreamReader reader = new StreamReader(pipeServer, Encoding.UTF8))
             using (StreamWriter writer = new StreamWriter(pipeServer, Encoding.UTF8) { AutoFlush = true })
             {
                 while (pipeServer.IsConnected)
                 {
                     string message = await reader.ReadLineAsync();
                     string[] CastiPrikazu = message.Split(' ');

                     switch (CastiPrikazu[0])
                     {
                         case "Ahoj":
                             writer.WriteLine("ahoj");
                             break;
                     }
                 }
             }
         }
     }
 }

Here is client code:

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
        {
            Console.WriteLine("Connecting to service...");
            await client.ConnectAsync();

            using (StreamWriter writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true })
            using (StreamReader reader = new StreamReader(client, Encoding.UTF8))
            {
                while (true)
                {
                    Console.Write("Type Message: ");
                    string message = Console.ReadLine();
                    await writer.WriteLineAsync(message);
                    string response = await reader.ReadLineAsync();
                    Console.WriteLine($"[ANSWER]: {response}");
                }
            }
        }     
    }
}

I am making Windows service in C#, and I need to communicate with this service using NamedPipeServerStream. When I start this service, connecting to it is without any problem. When I close the client and reopen it, I cannot reconnect to this service. Where is the problem?

Here is server code:

private async Task StartPipeServer()
 {
     while (true)
     {
         PipeSecurity pipeSecurity = new PipeSecurity();
         pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
         using (var pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, pipeSecurity))
         {
             await pipeServer.WaitForConnectionAsync();
             using (StreamReader reader = new StreamReader(pipeServer, Encoding.UTF8))
             using (StreamWriter writer = new StreamWriter(pipeServer, Encoding.UTF8) { AutoFlush = true })
             {
                 while (pipeServer.IsConnected)
                 {
                     string message = await reader.ReadLineAsync();
                     string[] CastiPrikazu = message.Split(' ');

                     switch (CastiPrikazu[0])
                     {
                         case "Ahoj":
                             writer.WriteLine("ahoj");
                             break;
                     }
                 }
             }
         }
     }
 }

Here is client code:

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
        {
            Console.WriteLine("Connecting to service...");
            await client.ConnectAsync();

            using (StreamWriter writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true })
            using (StreamReader reader = new StreamReader(client, Encoding.UTF8))
            {
                while (true)
                {
                    Console.Write("Type Message: ");
                    string message = Console.ReadLine();
                    await writer.WriteLineAsync(message);
                    string response = await reader.ReadLineAsync();
                    Console.WriteLine($"[ANSWER]: {response}");
                }
            }
        }     
    }
}
Share Improve this question asked Mar 14 at 15:07 Radim KrejčiříkRadim Krejčiřík 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

To see what's actually happening, you need to run both server and client via a debugger.

If the other end of the pipe disconnects while ReadLineAsync() is waiting, it will return null.
So the server crashes after a client disconnects.
Also, the server disposing of TextWriter can throw an error (trying to flush its buffer to a closed pipe).

Add some error handling for these two cases and the server should run for longer.

发布评论

评论列表(0)

  1. 暂无评论