Named pipes usage. Multiple clients, one server, multiple parallel requests

戏子无情 提交于 2020-01-03 06:49:09

问题


I'm trying to implement a named pipes server in .NET. The client will be C++. The nature of the data sent is not relevant to the question.

My first naive implementation looks something like:

using (NamedPipeServerStream stream = 
                new NamedPipeServerStream(PipeName,
                                          PipeDirection.InOut, 
                                          numberOfListeners,
                                          PipeTransmissionMode.Message))
{
     while (true)
     {
          try
          {
              stream.WaitForConnection();

              var request = ReadRequest(stream);

              var reply = Process(request);
              WriteReply(stream, reply);
              stream.WaitForPipeDrain();
          }
          catch (Exception ex)
          {
              //TO DO: log
          }
     }
 }

Am I approaching this right?

What would happen when two clients open a connection at the same time ?

Will they share the same stream and data will be intermingled ?

How can I avoid this?

Any ideas or resources on this will help. I'm pretty new to this topic.


回答1:


You will want the server to be able to handle concurrent client connections, and each client to connect to the server on a different instance of the pipe, rather than trying to do everything on one pipe instance as your code does at present. When the client is finished, you want to release the instance of the pipe used when talking to that client, not reuse it.

This answer gives a pseudo-code outline of one way to do this.

Also note that in Message mode you need to read from the pipe in a loop, until the IsMessageComplete property becomes true. It's the only way to guarantee you get each complete message. Also be aware that "message" in message mode means a stream of bytes written by the sender in one Write call to the pipe.

Client streams can't get mixed up with each other: a pipe instance has just two ends, THE client and THE server.



来源:https://stackoverflow.com/questions/5584211/named-pipes-usage-multiple-clients-one-server-multiple-parallel-requests

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