从内存中读取二进制文件行

时间:2017-05-18 10:13:03

标签: c# memory tcp binary client

我想从我的服务器模块发送二进制文件(Test.bin)到我的Client Executeable,它存储在内存中。在服务器端(C#)我创建.bin如下:

public static bool Write(string fileName, string[] write)
{
    try
    {
        using (BinaryWriter binWriter = new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            // each write-Array-Segment contains a 256 char string
            for (int i = 0; i < write.Length; i++)
                binWriter.Write(write[i] + "\n");
        }

        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

然后我将它发送给客户:

byte[] buffer = File.ReadAllBytes(Program.testFile /*Test.bin*/ );
byte[] bytes = BitConverter.GetBytes(buffer.Length);

if (BitConverter.IsLittleEndian)
    Array.Reverse((Array)bytes);

this.tcpClient.GetStream().Write(bytes, 0, 4);
this.tcpClient.GetStream().Write(buffer, 0, buffer.Length);

this.tcpClient.Close();

在客户端(C ++),我收到它并将其存储为:

DWORD UpdateSize = 0;
NetDll_recv(XNCALLER_SYSAPP, Sock, (char*)&UpdateSize, 4, 0); // what's being first received

unsigned char* Update = new unsigned char[UpdateSize];
if (UpdateSize == 0 || !Network_Receive(Sock, Update, UpdateSize) /*Downloading file into "Update"*/ )
{
    Sleep(2000);
    Network_Disconnect(Sock);
    printf("Failed to download file.\n");
}

这一切都运作良好。现在问题是:

我如何读取线路,我写入服务器端的文件,到客户端的数组?我不想将文件存储在客户端设备上并使用Streamreader,我想从内存中读取它!

非常感谢任何帮助! (提供一些代码可能是最好的)

1 个答案:

答案 0 :(得分:0)

由于您将字符串序列化为二进制流,因此我将采用以下方法。对于数组中的每个字符串:

  • 序列化字符串的大小
  • 序列化字符串 (你不需要任何分隔符)。

在C ++客户端中,当您收到流时:

  • 只读取大小(要读取的字节数取决于整数大小)
  • 当你有这个大小时,你会读取指定字节的数量,以便重新构建字符串

然后,继续读取大小,然后读取相应的字符串,直到字节流结束。

根据要求提供了一个简单的例子:

string[] parts = new string[]
{
    "abcdefg",
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit.Maecenas viverra turpis mauris, nec aliquet ex sodales in.",
    "Vivamus et quam felis. Vestibulum sit amet enim augue.",
    "Sed tincidunt felis nec elit facilisis sagittis.Morbi eleifend feugiat leo, non bibendum dolor faucibus sed."
};
MemoryStream stream = new MemoryStream();
// serialize each string as a couple of size/bytes array.
BinaryWriter binWriter = new BinaryWriter(stream);
foreach (var part in parts)
{
    var bytes = UTF8Encoding.UTF8.GetBytes(part);
    binWriter.Write(bytes.Length);
    binWriter.Write(bytes);
}

// read the bytes stream: first get the size of the bytes array, then read the bytes array and convert it back to a stream.
stream.Seek(0, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(stream);
while (stream.Position < stream.Length)
{
    int size = reader.ReadInt32();
    var bytes = reader.ReadBytes(size);
    var part = UTF8Encoding.UTF8.GetString(bytes);
    Console.WriteLine(part);
}
stream.Close();
Console.ReadLine();