Vincent Dagpin
Vincent Dagpin

Reputation: 3611

Encoding.ASCII.GetString() Problem VB.NET

i got a problem when receiving data from networkstream that was converted from bytes to string.. the output would be the same but when i compare the the string generated from Encoding.ASCII.GetString() compared to the actual string, the output is not the same..

this is my code..

Server:

Dim tcp As New TcpClient
tcp = findTCP(ip)
Dim ns As NetworkStream = tcp.GetStream
Dim b As [Byte]() = Encoding.ASCII.GetBytes("a")
ns.Write(b, 0, b.Length)
Dim bb(tcp.ReceiveBufferSize) As Byte
ns.Read(bb, 0, tcp.ReceiveBufferSize)
If Encoding.ASCII.GetString(bb) = "b" Then
    a = "conn"
Else
    a = "not"
End If

Client:

Dim ns As NetworkStream = socClient.GetStream
Dim b(socClient.ReceiveBufferSize) As Byte
ns.Read(b, 0, socClient.ReceiveBufferSize)

Dim bb As [Byte]() = Encoding.ASCII.GetBytes("b")
ns.Write(bb, 0, bb.Length)

just for ping purposes.. :)

my server pings to client..

is there any instance that when the string will be converted to bytes, the string will change? :?

Upvotes: 0

Views: 4684

Answers (2)

Guffa
Guffa

Reputation: 700562

You are ignoring the return value of the Read method, which would tell you how many bytes it actually did read. Everything after that in the buffer is garbage. Also it would tell you if you have read all of the stream or not, so you have no idea if you read all the data, or how much data there is.

Use the return value of the Read method to determine what you get, and whether you need to call it again. Assuming that an array of 1000 bytes is enough to hold the stream, this should work:

Dim bb(999) As Byte
Dim pos As Integer = 0
Dim len As Integer
Do
  len = ns.Read(bb, pos, bb.Length - pos)
  pos += len
Loop While len > 0

You also need to use that length when you decode the data, or you will decode the entire buffer, including the garbage after the actual data:

Encoding.ASCII.GetString(bb, 0, len)

Upvotes: 2

Kasper Holdum
Kasper Holdum

Reputation: 13363

Your byte arrays are declared far too large. This causes the strings to have extra appended characters which would mess with your string comparison logic.

ReceivedBufferSize is the buffer size internally in the socket and will usually have a value ranging from 2.000-8000 bytes. You should instead use the Available property which indicates how many bytes that are currently received.

Dim bb(tcp.Available) As Byte

Upvotes: 1

Related Questions