UnT*_*aDe 2 c# rpc ipc named-pipes
我在我正在处理的项目中使用命名管道,双方都是用 C# 编写的(客户端和服务器),并且都在同一台计算机上(命名管道用于 RPC)。两侧的命名管道设置为使用“PipeTransmissionMode.Message”模式,根据我的理解,该模式应该将传递给 pipe.Write() 的每个数据块“打包”在一条消息中,并将 pipe.Read() 放在另一端应该接收整个消息或不接收任何消息。
在尝试对接收端的数据进行反序列化时,我看到我得到了大量数据,比我发送的数据包还要大。于是我做了一个小测试,我创建了两个Application,server和client,看起来是这样的:
服务器:
class Program
{
static void Main(string[] args)
{
NamedPipeServerStream pipe = new NamedPipeServerStream("TestPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024);
pipe.WaitForConnection();
Random random = new Random();
while(true)
{
byte[] buffer = new byte[32];
random.NextBytes(buffer);
pipe.Write(buffer, 0, buffer.Length);
Console.WriteLine(buffer.Length);
}
}
}
Run Code Online (Sandbox Code Playgroud)
客户:
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "TestPipe", PipeDirection.InOut, PipeOptions.Asynchronous);
pipe.Connect();
while(true)
{
byte[] buffer = new byte[2048];
int read = pipe.Read(buffer, 0, buffer.Length);
Console.WriteLine(read);
if(read > 32)
Console.WriteLine("Big");
}
}
}
Run Code Online (Sandbox Code Playgroud)
运行这个,服务器只输出 32(这是我所期望的),但客户端有时输出 64,然后是“Big”。这是怎么回事?
PS:如果我放入Thread.Sleep(100)服务器循环,它会按预期工作(两边只写 32)
编辑:如果我Thread.Sleep(100)在服务器和Thread.Sleep(200)客户端上放置一个,我会更频繁地收到更大的数据包,这让我相信如果在调用 read 之前到达了不止一条消息,则 read 会返回所有消息。如何确保每次读取仅返回一条消息?
你忘了设置ReadMode到Message还有:
pipe.ReadMode = PipeTransmissionMode.Message;
Run Code Online (Sandbox Code Playgroud)
创建或连接到管道时Byte,无论TransmissionMode设置如何,默认模式始终为。