2017-05-18 41 views
0

我想從我的服務器模塊發送一個二進制文件(Test.bin)到我的客戶端可執行文件,它存儲在內存中。在服務器端(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,我想從內存中讀取它!

任何幫助,非常感謝! (提供一些代碼可能是最好的)

+0

確定二進制數據不能包含一個換行符? –

+0

它確實包含一個換行符「\ n」... – xTyrion

回答

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(); 
+0

您是否可以複製和修改我的代碼?因爲我不明白你的意思:/ – xTyrion

+0

我在C#中添加了一個簡單的示例。 –

+0

https://pastebin.com/X1u3bBFx不適用於我:( – xTyrion