命名管道的使用。多个客户端,一台服务器,多个并行的请求多个、一台、管道、客户端

2023-09-04 08:05:44 作者:风来就分开

我想实现.NET命名管道服务器。该客户端将C ++。发送的数据的性质是不相关的问题。

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?

对此有何想法或资源将帮助。我是pretty的新的这个话题。

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

推荐答案

您会希望服务器能够处理的并发客户端连接,而每个客户端连接到服务器上的管道,不同的实例,而不是试图尽在一个管道实例为您的code确实为present。当客户端完成后,要释放交谈时,该客户端使用的管道的实例,而不是重复使用。

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答案给人的一种方式的伪code轮廓做到这一点。

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

另外请注意,在消息模式,你需要从一个循环管道读,直到 IsMessageComplete 属性将变为。这是保证你每完成消息的唯一途径。另外要注意,在消息模式信息是指在一个写寄件人调用管道。

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.