sign in | join about | help | sitemap
Connecting Tech Pros Worldwide
kevin21388's Avatar

Excess buffer space removal


Question posted by: kevin21388 (Newbie) on August 27th, 2008 04:03 PM
I am getting say a persons name over a tcp connection. The problem is that when I do this :
Expand|Select|Wrap|Line Numbers
  1.             Dim buffSize As Integer
  2.             Dim inStream(10024) As Byte
  3.             buffSize = playerSockets(connectionCount).ReceiveBufferSize
  4.             playerStreams(connectionCount).Read(inStream, 0, buffSize)
  5.             Dim curName As String=System.Text.Encoding.ASCII.GetString   (inStream)

The curName string has a length of 10025. How do I get rid of excess blank space in either the byte array I recieve the data in or the string after I convert it?
8 Answers Posted
insertAlias's Avatar
insertAlias August 27th, 2008 04:06 PM
Moderator - 1,874 Posts
#2: Re: Excess buffer space removal

can you .Trim() the resulting string?
kevin21388's Avatar
kevin21388 August 27th, 2008 04:07 PM
Newbie - 7 Posts
#3: Re: Excess buffer space removal

How would I know when the string's data end and excess space starts? the length function returns 10025.
Plater's Avatar
Plater August 27th, 2008 04:18 PM
Moderator - 6,022 Posts
#4: Re: Excess buffer space removal

Why are you trying to read in the buffersize? Why not try reading in the amount of data on the stream?
This is like the 3rd question I have seen about tcp connection where people are trying to read buffersize amount of bytes and getting excess data (since they asked for buffersize amount of data) instead of reading the correct amount.
Where did you learn this way of doing things? I feel as though I need to track down the source and have them correct their error.
insertAlias's Avatar
insertAlias August 27th, 2008 04:18 PM
Moderator - 1,874 Posts
#5: Re: Excess buffer space removal

Looks like I misread your question. Please disregard.
kevin21388's Avatar
kevin21388 August 27th, 2008 04:22 PM
Newbie - 7 Posts
#6: Re: Excess buffer space removal

How do I get the recieveDataSize?
If you really want to know I was using this site as a reference on how to do the TCP connections:
http://vb.net-informations.com/comm...rver_Socket.htm
Last edited by kevin21388 : August 27th, 2008 at 04:25 PM. Reason: Add Info
balabaster's Avatar
balabaster August 27th, 2008 05:14 PM
Expert - 632 Posts
#7: Re: Excess buffer space removal

Quote:
Originally Posted by kevin21388
How do I get the recieveDataSize?
If you really want to know I was using this site as a reference on how to do the TCP connections:
http://vb.net-informations.com/comm...rver_Socket.htm


If you're using the asynchronous BeginReceive, EndReceive methods to receive data and hold your asynchronous data, then the BytesRead method returns the actual number of bytes read from the tcp connection as opposed to the size of the buffer.

I've cut and pasted some code from an application I wrote a year or two ago now that demonstrates the BeginReceive and EndReceive. The BeginReceive is initiated in the OnConnected sub, you didn't need all of the code, and most of it probably won't make sense, but I thought the complete subs would give you a little more context as to how it is used. The EndReceive is found in the OnReceiveData sub which is actually a callback which is fired as a delegate of the BeginReceive method.

A simplified example is this:

Expand|Select|Wrap|Line Numbers
  1. Dim SessionObject As New MyCustomSessionObject
  2.  
  3. Sub StartListening()
  4.   Dim Socket As TcpSocket
  5.   Dim UserObject As New MyCustomUserObject
  6.   'Usage:
  7.   '  BeginReceive(
  8.   '    BufferToReceiveTo, 'The buffer to receive the data do
  9.   '    PositionToStartReadAt, 'The offset at which to begin reading from the buffer
  10.   '    BufferSize, 'An integer describing the length of the receive buffer
  11.   '    SocketFlags, 'Don't remember what this is, but I set it to none, it works.
  12.   '    CallbackDelegate, 'This is fired when data is received
  13.   '    SessionObject 'An object to hold asynchronous session specific data
  14.   '  )
  15.   '
  16.   ' Stuff needed to set up TCP connection or this won't work...
  17.   '
  18.   Socket.BeginReceive(SessionObject.ReadBuffer, 0, UserObject.BufferSize,   SocketFlags.None, AddressOf OnReceiveData, SessionObject)
  19. End Sub
  20.  
  21. Sub OnReceiveData()
  22.   bytesRead = oSocket.EndReceive(IAResult)
  23.   Dim thisRead() As Byte
  24.   thisRead = TruncateByteArray(SessionObject.ReadBuffer, 0, bytesRead)
  25.   SessionObject.Binary = JoinByteArrays(SessionObject.Binary, thisRead)
  26. End Sub
  27.  
  28. Private Function TruncateByteArray(ByVal Input() As Byte, ByVal StartIndex As UInt64, ByVal Count As UInt64) As Byte()
  29.  
  30.   'Do stuff to truncate your byte array to just the part starting at StartIndex to the correct length.
  31.  
  32. End Function
  33.  
  34. Private Function JoinByteArrays(ByVal array1() As Byte, ByVal array2() As Byte) As Byte()
  35.  
  36.   'Do stuff to join together two byte arrays...
  37.  
  38. End Function
  39.  



The code below is the actual code cut and pasted from my application:

Expand|Select|Wrap|Line Numbers
  1.     Private Sub OnConnected(ByVal IAResult As IAsyncResult)
  2.  
  3.         Dim oListener As TcpListener = CType(IAResult.AsyncState, TcpListener)
  4.         Dim sEvent As String = ""
  5.  
  6.         Try
  7.             Dim oSocket As Socket = oListener.EndAcceptSocket(IAResult)
  8.  
  9.             Dim oRemoteEP As IPEndPoint = oSocket.RemoteEndPoint
  10.             sEvent = String.Format("[{0}:{1}] Connected.", oRemoteEP.Address.ToString, oRemoteEP.Port)
  11.             ReportEvent(sEvent, EventLogEntryType.Information, LogPriority.Low)
  12.  
  13.             'oSocket.ReceiveTimeout = 60000
  14.             'oSocket.SendTimeout = 60000
  15.  
  16.             clientConnected.Set()
  17.  
  18.             Dim oSession As New UserSession(_OutputDirectory)
  19.             AddHandler oSession.CaptureStarted, AddressOf OnCaptureEvent
  20.             AddHandler oSession.CaptureStopped, AddressOf OnCaptureEvent
  21.             AddHandler oSession.CaptureFailed, AddressOf OnCaptureEvent
  22.  
  23.             Dim DisplayMsg As MsgBoxResult
  24.             If _ListenerMode Then DisplayMsg = MsgBox("An incoming connection request has been received from " & oRemoteEP.Address.ToString & " do you wish to accept this request?", MsgBoxStyle.Information Or MsgBoxStyle.YesNo, "Confirm.")
  25.  
  26.             If (Not _ListenerMode) Or (DisplayMsg = MsgBoxResult.Yes) Then
  27.  
  28.                 oSession.ActiveSocket = oSocket
  29.                 oSession.RemoteAddress = oSocket.RemoteEndPoint
  30.  
  31.                 'Add this session to the array so we shut it down
  32.                 'correctly when we close down.
  33.                 _Sessions.Add(oSession)
  34.  
  35.                 oSocket.BeginReceive(oSession.ReadBuffer, 0, UserSession.BufferSize, SocketFlags.None, AddressOf OnReceiveData, oSession)
  36.  
  37.             Else
  38.  
  39.                 SendASCII(oSession, "Info", "Connection request denied by user of remote host.")
  40.                 oSocket.Disconnect(True)
  41.  
  42.             End If
  43.  
  44.         Catch e As Exception
  45.             sEvent = e.Message
  46.             ReportEvent(sEvent, EventLogEntryType.Error, LogPriority.Low)
  47.  
  48.         End Try
  49.  
  50.     End Sub
  51.  
  52.     Private Sub OnReceiveData(ByVal IAResult As System.IAsyncResult)
  53.  
  54.         Dim oSession As UserSession = CType(IAResult.AsyncState, UserSession)
  55.         oSession.Refresh()
  56.  
  57.         Dim oSocket As Socket = oSession.ActiveSocket
  58.         Dim bytesRead As Int32 = 0
  59.  
  60.         Try
  61.             bytesRead = oSocket.EndReceive(IAResult)
  62.  
  63.             If bytesRead > 0 Then
  64.  
  65.                 Dim thisRead() As Byte
  66.                 thisRead = TruncateByteArray(oSession.ReadBuffer, 0, bytesRead)
  67.                 oSession.Binary = JoinByteArrays(oSession.Binary, thisRead)
  68.  
  69.                 If ProtocolBuilder.HasProtocolSignature(oSession.Bina  ry) Then
  70.  
  71.                     If ProtocolBuilder.IsEOF(oSession.Binary) Then
  72.  
  73.                         Call CommandProcessor(oSession)
  74.                         oSession.Binary = Nothing
  75.  
  76.                     End If
  77.  
  78.                     'Tell the socket that we want to continue listening and skip out of the sub
  79.                     oSocket.BeginReceive(oSession.ReadBuffer, 0, UserSession.BufferSize, SocketFlags.None, AddressOf OnReceiveData, oSession)
  80.  
  81.                 Else
  82.                     'Boot the session
  83.                     oSocket.BeginDisconnect(True, AddressOf OnDisconnected, oSession)
  84.  
  85.                 End If
  86.  
  87.             End If
  88.  
  89.         Catch e As Exception
  90.             If oSocket.Connected Then
  91.                 oSocket.BeginDisconnect(True, AddressOf OnDisconnected, oSession)
  92.             Else
  93.                 oSession.ActiveSocket = Nothing
  94.                 oSession = Nothing
  95.             End If
  96.         End Try
  97.  
  98.     End Sub


Hopefully that will point you in the right direction. It's not complete by any means, if you don't have your head around delegates and asynchronous callbacks, then you're going to have to get your head around those concepts first before much of this will make sense.
Plater's Avatar
Plater August 27th, 2008 05:20 PM
Moderator - 6,022 Posts
#8: Re: Excess buffer space removal

Well, it would depend on your object, but it's really pretty simple/straightforward.
Try the .Available property on a TcpClient or a Socket object
kevin21388's Avatar
kevin21388 August 27th, 2008 06:08 PM
Newbie - 7 Posts
#9: Re: Excess buffer space removal

Thanks balabaster, I will keep this code in mind while I finish the app. There is some very useful stuff in there.

Also thanks to plater, the available attribute is exactly what I was looking for.
Last edited by kevin21388 : August 27th, 2008 at 06:09 PM. Reason: Adding thanks
Reply
Not the answer you were looking for? Post your question . . .
197,034 members ready to help you find a solution.
Join Bytes.com

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 197,034 network members.
Post your question now . . .
It's fast and it's free

Popular Articles

Top .NET Contributors