Could you please explain why the Output window does not print the "xxxxx" part of the string? Looks like I'm missing some basic understanding about something...?
I'm sending string messages over TcpClient, and when building the strings, I don't add any special characters on the sender side, and neither on the receiver side. Is this part of the problem?
http://i56.tinypic.com/9lg7pi.png
EDIT:
I'm building my strings at the sender side like this:
Private Sub SendData(ByVal stringArray As String())
SendData(GetMessageString(stringArray))
End Sub
Public Function GetMessageString(ByVal array As String()) As String
Dim str As String = ""
For i = 0 To array.Length - 1
str = str & array(i)
If i < array.Length - 1 Then
str = str & "|"
End If
Next
Return str
End Function
And on receiving side, the variable is built:
client.GetStream.BeginRead(readBodyBuffer, 0, MESSAGE_BODY_LENGTH, New AsyncCallback(AddressOf ReadBody), Nothing)
...
Private Sub ReadBody(ByVal aread As IAsyncRe开发者_如何学Pythonsult)
BytesRead = client.GetStream.EndRead(aread)
...
' Read (add) into buffer
messagePart = Encoding.ASCII.GetString(readBodyBuffer)
messagePart = messagePart & "xxxxx"
EDIT 3
My simple mistake was wrong use of Redim of the byte array: (parameter 10 gives 11 elements)
Wrong:
ReDim readBodyBuffer(MESSAGE_BODY_LENGTH)
Correct:
ReDim readBodyBuffer(MESSAGE_BODY_LENGTH - 1)
I believe it is somehow related to non-printable characters. For example this C# code:
string message = "Hello\0 Hello2";
Debug.Print(message);
Here I have a string with null character at the end. In debug visualizer it displays in the same way as I created this string - "Hello\0 Hello2"
. But in output window it doesn't display \0
and even truncates Hello 2
. So I think it relates to your issue though I couldn't reproduce it completely. Check your messagePart.Length
.
UPDATE: Ok, so after going through all these comments here and in another answer I think that the issue is caused by incorrect usage of readBodyBuffer
. It depends on how you allocate this buffer, but I expect that you're simply creating a new byte array with fixed (11) length. Then you're ignoring the number of bytes which were actually received (10) and converting string from that array using ASCII encoding. The fact that BytesRead
less than allocated buffer size causes the fact that last byte in array is zero. You should use Encoding.ASCII.GetString
method which accepts length
argument so you won't receive \0
in result string:
messagePart = Encoding.ASCII.GetString(readBodyBuffer, 0, ReadBytes)
Agree with Snowbear.
Could you print char code of the white space in your message? It should be 32 for the space.
Debug.Print(AscW(messagePart(10)))
精彩评论