Excess buffer space removal

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kevin21388
    New Member
    • Aug 2008
    • 9

    Excess buffer space removal

    I am getting say a persons name over a tcp connection. The problem is that when I do this :
    Code:
                Dim buffSize As Integer
                Dim inStream(10024) As Byte
                buffSize = playerSockets(connectionCount).ReceiveBufferSize
                playerStreams(connectionCount).Read(inStream, 0, buffSize)
                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?
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    can you .Trim() the resulting string?

    Comment

    • kevin21388
      New Member
      • Aug 2008
      • 9

      #3
      How would I know when the string's data end and excess space starts? the length function returns 10025.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        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.

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          Looks like I misread your question. Please disregard.

          Comment

          • kevin21388
            New Member
            • Aug 2008
            • 9

            #6
            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:
            Last edited by kevin21388; Aug 27 '08, 03:25 PM. Reason: Add Info

            Comment

            • balabaster
              Recognized Expert Contributor
              • Mar 2007
              • 798

              #7
              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/commu...ver_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:

              Code:
              Dim SessionObject As New MyCustomSessionObject
              
              Sub StartListening()
                Dim Socket As TcpSocket
                Dim UserObject As New MyCustomUserObject
                'Usage:
                '  BeginReceive(
                '    BufferToReceiveTo, 'The buffer to receive the data do
                '    PositionToStartReadAt, 'The offset at which to begin reading from the buffer
                '    BufferSize, 'An integer describing the length of the receive buffer
                '    SocketFlags, 'Don't remember what this is, but I set it to none, it works.
                '    CallbackDelegate, 'This is fired when data is received
                '    SessionObject 'An object to hold asynchronous session specific data
                '  )
                '
                ' Stuff needed to set up TCP connection or this won't work...
                '
                Socket.BeginReceive(SessionObject.ReadBuffer, 0, UserObject.BufferSize,   SocketFlags.None, AddressOf OnReceiveData, SessionObject)
              End Sub
              
              Sub OnReceiveData()
                bytesRead = oSocket.EndReceive(IAResult)
                Dim thisRead() As Byte
                thisRead = TruncateByteArray(SessionObject.ReadBuffer, 0, bytesRead)
                SessionObject.Binary = JoinByteArrays(SessionObject.Binary, thisRead)
              End Sub
              
              Private Function TruncateByteArray(ByVal Input() As Byte, ByVal StartIndex As UInt64, ByVal Count As UInt64) As Byte()
              
                'Do stuff to truncate your byte array to just the part starting at StartIndex to the correct length.
              
              End Function
              
              Private Function JoinByteArrays(ByVal array1() As Byte, ByVal array2() As Byte) As Byte()
              
                'Do stuff to join together two byte arrays...
              
              End Function

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

              Code:
                  Private Sub OnConnected(ByVal IAResult As IAsyncResult)
              
                      Dim oListener As TcpListener = CType(IAResult.AsyncState, TcpListener)
                      Dim sEvent As String = ""
              
                      Try
                          Dim oSocket As Socket = oListener.EndAcceptSocket(IAResult)
              
                          Dim oRemoteEP As IPEndPoint = oSocket.RemoteEndPoint
                          sEvent = String.Format("[{0}:{1}] Connected.", oRemoteEP.Address.ToString, oRemoteEP.Port)
                          ReportEvent(sEvent, EventLogEntryType.Information, LogPriority.Low)
              
                          'oSocket.ReceiveTimeout = 60000
                          'oSocket.SendTimeout = 60000
              
                          clientConnected.Set()
              
                          Dim oSession As New UserSession(_OutputDirectory)
                          AddHandler oSession.CaptureStarted, AddressOf OnCaptureEvent
                          AddHandler oSession.CaptureStopped, AddressOf OnCaptureEvent
                          AddHandler oSession.CaptureFailed, AddressOf OnCaptureEvent
              
                          Dim DisplayMsg As MsgBoxResult
                          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.")
              
                          If (Not _ListenerMode) Or (DisplayMsg = MsgBoxResult.Yes) Then
              
                              oSession.ActiveSocket = oSocket
                              oSession.RemoteAddress = oSocket.RemoteEndPoint
              
                              'Add this session to the array so we shut it down
                              'correctly when we close down.
                              _Sessions.Add(oSession)
              
                              oSocket.BeginReceive(oSession.ReadBuffer, 0, UserSession.BufferSize, SocketFlags.None, AddressOf OnReceiveData, oSession)
              
                          Else
              
                              SendASCII(oSession, "Info", "Connection request denied by user of remote host.")
                              oSocket.Disconnect(True)
              
                          End If
              
                      Catch e As Exception
                          sEvent = e.Message
                          ReportEvent(sEvent, EventLogEntryType.Error, LogPriority.Low)
              
                      End Try
              
                  End Sub
              
                  Private Sub OnReceiveData(ByVal IAResult As System.IAsyncResult)
              
                      Dim oSession As UserSession = CType(IAResult.AsyncState, UserSession)
                      oSession.Refresh()
              
                      Dim oSocket As Socket = oSession.ActiveSocket
                      Dim bytesRead As Int32 = 0
              
                      Try
                          bytesRead = oSocket.EndReceive(IAResult)
              
                          If bytesRead > 0 Then
              
                              Dim thisRead() As Byte
                              thisRead = TruncateByteArray(oSession.ReadBuffer, 0, bytesRead)
                              oSession.Binary = JoinByteArrays(oSession.Binary, thisRead)
              
                              If ProtocolBuilder.HasProtocolSignature(oSession.Binary) Then
              
                                  If ProtocolBuilder.IsEOF(oSession.Binary) Then
              
                                      Call CommandProcessor(oSession)
                                      oSession.Binary = Nothing
              
                                  End If
              
                                  'Tell the socket that we want to continue listening and skip out of the sub
                                  oSocket.BeginReceive(oSession.ReadBuffer, 0, UserSession.BufferSize, SocketFlags.None, AddressOf OnReceiveData, oSession)
              
                              Else
                                  'Boot the session
                                  oSocket.BeginDisconnect(True, AddressOf OnDisconnected, oSession)
              
                              End If
              
                          End If
              
                      Catch e As Exception
                          If oSocket.Connected Then
                              oSocket.BeginDisconnect(True, AddressOf OnDisconnected, oSession)
                          Else
                              oSession.ActiveSocket = Nothing
                              oSession = Nothing
                          End If
                      End Try
              
                  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.

              Comment

              • Plater
                Recognized Expert Expert
                • Apr 2007
                • 7872

                #8
                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

                Comment

                • kevin21388
                  New Member
                  • Aug 2008
                  • 9

                  #9
                  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; Aug 27 '08, 05:09 PM. Reason: Adding thanks

                  Comment

                  Working...