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 :
-
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?
8
Answers Posted
can you .Trim() the resulting string?
How would I know when the string's data end and excess space starts? the length function returns 10025.
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.
Looks like I misread your question. Please disregard.
Last edited by kevin21388 : August 27th, 2008 at 04:25 PM.
Reason: Add Info
Quote:
Originally Posted by kevin21388
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:
-
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:
-
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.Bina ry) 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.
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
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
|
|
|
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.
|