Get the actual data length read from network stream

RadhaKrishnaKiJaya used Ask the Experts™
Hi Experts,

I am reading data from a RFID reader using network stream. But the length of the data is always 8193. What can I do to get the actual length.
Thanks in advance.

Dim tcpClient As New TcpClient("", "10001")
             Dim netStream As NetworkStream = TcpClient.GetStream()
             If netStream.CanRead Then
                 ' Reads the NetworkStream into a byte buffer.
                 Dim bytes(TcpClient.ReceiveBufferSize) As Byte
                 ' Read can return anything from 0 to numBytesToRead.  
                 ' This method blocks until at least one byte is read.
                 netStream.Read(bytes, 0, CInt(TcpClient.ReceiveBufferSize))

                 ' Returns the data received from the host to the console.
                Dim ReturnData As String = Encoding.ASCII.GetString(bytes)
                 TextBox1.Text = ReturnData  'Length is always 8193
                RaiseEvent TCPDataIn(ReturnData)
                 Console.WriteLine("You cannot read data from this stream.")
                 ' Closing the tcpClient instance does not close the network stream.
             End If
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
NetworkStream.Read returns thenumber of bytes read, which you are not storing.

Dim numberOfBytesRead As Integer = 0
' ... as before
numberOfBytesRead = netStream.Read(bytes, 0, CInt(TcpClient.ReceiveBufferSize))

Open in new window

You are then free to use numberOfBytesRead in your output or to examine it.
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009

Adding to mrwad99's answer, use "numberOfBytesRead" in Encoding.ASCII.GetString():
Dim ReturnData As String = Encoding.ASCII.GetString(bytes, 0, numberOfBytesRead)

Open in new window


Thank you very much. It worked.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial