2016-10-12 102 views
0

我合併了一個string的字節和那個長度的字節string Ex。 stackoverflow13(可讀的stackoverflow的字節加上長度爲13的字節的表示)現在這個組合字節將被髮送到另一個程序,該程序使用Encoding.UTF8.GetString(byte, index, count)我想分開stackoverflow13的索引count。我怎樣才能做到這一點。這是代碼:如何從一個字節流中分離一個字節

Dim text1() As Byte = Encoding.UTF8.GetBytes("stackoverflow") 
     Dim len1() As Byte = BitConverter.GetBytes(text1.Length) 
     Dim byteLen As Integer = text1.Length + len1.Length 
     Dim bStream(byteLen) As Byte 
     text1.CopyTo(bStream, 0) 
     len1.CopyTo(bStream, text1.Length) 
     '       | 
     '       | Byte stream "bStream" 
     '       V 
     '----------------------------------------------------------- 
     '--------------------Different program---------------------- 
     '----------------------------------------------------------- 
     '       | 
     '       | Byte stream "bStream" 
     '       | 
     '       |      | n = supposed to be len1 
     '       V      V  from the stream 
     Debug.WriteLine(Encoding.UTF8.GetString(bStream, 0, n)) 

我該如何做到這一點在類似的流多時間?防爆。

fileOne,fileOneLength,fileTwo,fileTwoLength...

+0

爲什麼你需要發送字符串長度? – Steve

+0

由於您未發送「stackoverflow13」,因此您的問題具有誤導性。您正在將整數轉換爲4個字節。您的流的最後4個字節將是該長度的整數。通常這在開始時作爲數據包標題發送。 –

回答

1

你能使用分隔符來告訴其他程序從哪裏開始尋找長度數據,如「 - 」,所以這將是「stackloverflow-13」。

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 

    ' Parsing using a delimeter 
    Dim text1() As Byte = Encoding.UTF8.GetBytes("stackoverflow" & "-") ' concatenate a delimter in the string 
    ' Convert to string, otherwise the program sends the byte value of 13 plus 3 padded zeros so you end up transmitting a Carriage return and 3 null characters 
    Dim len1() As Byte = Encoding.UTF8.GetBytes(text1.Length - 1.ToString) ' Subtract the delimteter character value from the total 
    Dim byteLen As Integer = text1.Length + len1.Length 
    Dim bStream(byteLen) As Byte 
    text1.CopyTo(bStream, 0) 
    len1.CopyTo(bStream, text1.Length) 


    ' This goes in the other program 
    Dim Str() As String = Encoding.UTF8.GetString(bStream, 0, bStream.Length).Split("-") 

    Dim Text As String = Str(0) 
    Dim Index As Integer = CInt(Str(1)) 


End Sub 
+0

這有幫助,但我發現我的代碼解決方法 – conquistador

相關問題