如何传递多个字节

问题描述 投票:1回答:2

我有两个可以通过named pipes相互通信的控制台应用程序,可以从NuGet下载,我找到了small example here

App1控制台:

static void Main(string[] args)
{
    SendByteAndReceiveResponse();
}     

private static void SendByteAndReceiveResponse()
{
    using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("test-pipe"))
    {
        namedPipeServer.WaitForConnection();
        namedPipeServer.WriteByte(1);
        int byteFromClient = namedPipeServer.ReadByte();
        Console.WriteLine(byteFromClient);
    }
}

Consoleapp2:

static void Main(string[] args)
{        
    ReceiveByteAndRespond();
}

  private static void ReceiveByteAndRespond()
{
    using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
    {
        namedPipeClient.Connect();
        Console.WriteLine(namedPipeClient.ReadByte());
        namedPipeClient.WriteByte(2);
    }            
}

我的问题:如何传递多个字节或多个变量?

c# named-pipes
2个回答
3
投票

您可以使用Write方法写入多个字节。问题是您不知道接收方的长度,因此您必须将其传递给服务器。

此代码适用于服务器。它将字节发送到客户端。首先它告诉了多少字节,然后它写入内容:

byte[] bytes = new byte[] { 1, 2, 3, 4 };
int length = bytes.Length;

byte[] lengthAsBytes = BitConverter.GetBytes(length);
namedPipeServer.Write(lengthAsBytes, 0, 4); // an int is four bytes

namedPipeServer.Write(bytes, 0, length);

然后在另一边,首先阅读长度,然后是内容:

byte[] lengthAsBytes = new byte[4]; // an int is four bytes
namedPipeServer.Read(lengthAsBytes, 0, 4);

int length = BitConverter.ToInt32(lengthAsBytes, 0);

byte[] bytes = new byte[length];
namedPipeServer.Read(bytes, 0, length);

0
投票

您可以使byte类型数组使用所需的字节数初始化它。然后在循环中使用namedPipeServer.Write(byte[] buffer, int offset, int count )迭代所有数组元素。

© www.soinside.com 2019 - 2024. All rights reserved.