Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Go Back  Xtreme Visual Basic Talk > > > Strange problem with string variable after conversion from byte array


Reply
 
Thread Tools Display Modes
  #1  
Old 05-23-2011, 06:15 PM
Schravendeel Schravendeel is offline
Newcomer
 
Join Date: Apr 2010
Posts: 19
Default Strange problem with string variable after conversion from byte array


Hello Everyone!

I have a strange problem with the following code:

Code:
 Private Sub Listener()
        Dim infiniteCounter As Integer
        Dim bytesFrom(8192) As Byte
        Dim dataFromClient As String
        RequestCount = 0
        For infiniteCounter = 1 To 2
            infiniteCounter = 1
            Try
                RequestCount += 1
                Dim networkStream As NetworkStream = ClientSocket.GetStream()
                networkStream.Read(bytesFrom, 0, CInt(ClientSocket.ReceiveBufferSize))
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
                Select Case dataFromClient
                    Case "PING_RESPONSE"
                        If Not LastPingTime = Nothing Then
                            Dim ts As TimeSpan = Date.Now - LastPingTime
                            _Ping = ts.Milliseconds
                            RaiseEvent Log("Received ping response from " & IP & " request took " & ts.Milliseconds & " ms.", Form1.LogType.DEBUG)
                            LastPingTime = Nothing
                        Else
                            RaiseEvent Log("Received ping response from " & IP & " but there was no request pending. Possible hacker?", Form1.LogType.SEVERE)
                        End If
                    Case Else
                        RaiseEvent DataReceived(Me, dataFromClient, dataFromClient.Length)
                End Select
            Catch ex As Exception
                        RaiseEvent ConnectionLost(Me, ex)
                        RaiseEvent Log("Lost connection from " & IP & ".", Form1.LogType.INFO)
                        Exit For
            End Try
        Next
    End Sub
When the client sends text to the server, this text gets stored in the dataFromClient variable. If I send "PING_RESPONSE" to the server it gets the string correctly; the value of the dataFromClient variable = PING_RESPONSE, but the length of this string is set to the buffer size (8192 + 1) and the code inside the Case "PING_RESPONSE" block doesn't fire. Does anybody have any ideas on why it is happening and how to fix this?
Reply With Quote
  #2  
Old 05-23-2011, 08:21 PM
AtmaWeapon's Avatar
AtmaWeaponStrange problem with string variable after conversion from byte array AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

A socket's ReceiveBufferSize property is the maximum number of bytes the socket can receive before it starts dropping packets. It has nothing to do with the amount of data that the socket receives.

Read the contract for NetworkStream.Read(). It reads up to size bytes from the stream and puts them in buffer starting at the position offset. In your case, bytesFrom has 8192 elements and stands for the buffer. The offset is 0. ReceiveBufferSize is some unknown number that serves as size. You get lucky, and there's less than 8193 bytes available and however many bytes there are get crammed into bytesFrom. You have no idea how many this is because you don't check the return value of Read(). Finally, you ask for the string represented by the bytes. Since there's 8193 bytes in the array, you get a string that contains the expected data and ends with lots of garbage. If you weren't lucky, there'd be more than 8193 bytes available and Read() would try to jam them all into a too small array.

Usually the documentation comes with examples. These show you how the code is intended to be used, and are only rarely a bad guide. Look at the example in the Read() documentation. Notice how they keep a small buffer, read its maximum possible bytes, then append that data to a string that is built on the fly? You should follow that pattern. Here's the skeleton:
Code:
Dim buffer(1023) As Byte
Dim builder As New Text.StringBuilder
Dim bytesRead As Integer
We've got a small buffer, an unlimited string builder, and a holding place for how many bytes were read.
Code:
Do
    bytesRead = yourStream.Read(buffer, 0, buffer.Length)
We're looping. Read() will read up to 1024 bytes and place them in buffer. If it reads less (like 123 bytes), it will return the number of bytes it read so we know where the end of the data in buffer is.
Code:
    Dim newFragment As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
This creates a string by interpreting the bytes that were read. If less than 1024 bytes were read, we only look at the parts of buffer that have data.
Code:
    builder.Append(newFragment)
Loop Until bytesRead = 0
We append that fragment to the string builder. If no bytes were read this is an empty string; no big deal. Finally, we exit the loop if no bytes were read; this generally indicates there's no more data. On a slower connection this is less reliable but we can discuss that if needed.
Code:
Dim finalString As String = builder.ToString()
A StringBuilder isn't a string, so before trying to use it as such make sure to convert it.

That's the general pattern for getting data at all using a network stream.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #3  
Old 05-24-2011, 04:57 AM
Schravendeel Schravendeel is offline
Newcomer
 
Join Date: Apr 2010
Posts: 19
Default

Thank you. I will try to use this method instead of the method I am currently using. But the text received really is "PING_RESPONSE" there is no garbage after that even if I write it to file it still is "PING_RESPONSE" nothing more and nothing less. (No garbage)

I added a screenshot to elaborate.
Attached Images
File Type: png screenshot_001.png (118.1 KB, 10 views)
Reply With Quote
  #4  
Old 05-24-2011, 09:18 AM
AtmaWeapon's Avatar
AtmaWeaponStrange problem with string variable after conversion from byte array AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

It could be that the first garbage character is the null byte (0x00). Strings tend to interpret this to mean "end of string", or at least the debugger does so. It's very possible to have a string length larger than what the debugger displays because of this.

Either way my explanation fits what's happening, so it can't hurt to try and see if I'm right.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
 
Strange problem with string variable after conversion from byte array
Strange problem with string variable after conversion from byte array
 
-->