How to use named pipes in C# correctly — several connections, server recreation etc

最后都变了- 提交于 2020-08-02 06:58:21

问题


I need to implement an inter-process communication between C# applications. I decided to use named pipes and wrote the following code:

Server

while (true)
{
    using (var server = new NamedPipeServerStream("some_pipe"))
    {
        server.WaitForConnection();
        using (var reader = new StreamReader(server))
        {
            string line = reader.ReadLine();
            MessageBox.Show(line);
        }
    }
}

Client

using (var client = new NamedPipeClientStream("some_pipe"))
{
    client.Connect();

    using (var writer = new StreamWriter(client))
    {
        writer.AutoFlush = true;
        writer.WriteLine(path);
        client.WaitForPipeDrain();
    }
}

I have the following questions about it:

  • Is this solution correct at all? Is there any issues or bugs you already see?
  • What will happen if the second client will try to connect to this server? Will it wait for the first client to finish or just send its message along with another client's instance resulting in garbage?
  • Should I really create another instance of NamedPipeServerStream class every time? If I move its construction from the while (true) loop it gives me an exception "Cannot access a closed pipe". How can I avoid it? If I can't avoid it and should re-create this object every time, what will happen if there is no NamedPipeServerStream at the moment when client will try to connect to it?

回答1:


This will not work. Multiple clients connecting to just one NamedPipeServerStream is a feature not available. Its name with "...ServerStream" is misleading. Pipes are 1 to 1 connections. You must have multiple server instances serving the same pipe for many clients. This Code Project shows how to implement a Server Pipes and may help you.



来源:https://stackoverflow.com/questions/32178016/how-to-use-named-pipes-in-c-sharp-correctly-several-connections-server-recre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!