2016-10-12 45 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

相关问题