I was trying to grab the string length of readData but when I try msgb开发者_C百科ox(readData.Length), its giving me a large numeric digit instead. Anyone care to help? Thanks.
Dim readData as string
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
readData = "" + returndata
msg()
You need to use the return value of Stream.Read, and only create the string from the bytes that have actually been read:
Dim bytesRead = serverStream.Read(inStream, 0, buffSize)
Dim text = Encoding.ASCII.GetString(inStream, 0, bytesRead)
Note, however, that you should usually keep reading from a stream until there's no more data to read. StreamReader
can help you do this really simply, if you're trying to convert everything to a string:
Dim text = new StreamReader(serverStream, Encoding.ASCII).ReadToEnd()
(I'm assuming you're closing the stream elsewhere; alternatively you should close the StreamReader
in a finally block.)
Are you absolutely sure that the data will always be ASCII, by the way? That means you'll never get any accented characters etc.
If anything is still unclear after reading mine and Guffa's answers, please post more details of exactly what you're trying to do.
You are making the quite common mistake of ignoring the return value from the Read
method.
The method will read data into the buffer, and return the number of bytes that was placed in the buffer. By ignoring that return value and decoding the entire buffer, the string will be as long as the buffer, and contain a lot of garbage data at the end.
Also, you have to call the Read
method repeatedly until it returns zero, as the method doesn't have to return all the data in one call.
Dim readData As string
Dim length As Integer = 0
Dim size As Integer
Do
size = serverStream.Read(inStream, length, buffSize - length)
length += size
Loop Until size = 0
readData = System.Text.Encoding.ASCII.GetString(inStream, 0, length)
MessageBox.Show(length.ToString())
MessageBox.Show(readData.Length.ToString())
As you are using the ASCII encoding, length
and readData.Length
will be the same, as each byte is decoded into one character. If you were using for example the UTF-8 encoding they could differ, as length
would be the number of bytes read and readData.Length
would be the number of character that those bytes were decoded into.
精彩评论