473,408 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Excess buffer space removal

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)
  6.  
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?
Aug 27 '08 #1
8 1616
Curtis Rutland
3,256 Expert 2GB
can you .Trim() the resulting string?
Aug 27 '08 #2
How would I know when the string's data end and excess space starts? the length function returns 10025.
Aug 27 '08 #3
Plater
7,872 Expert 4TB
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.
Aug 27 '08 #4
Curtis Rutland
3,256 Expert 2GB
Looks like I misread your question. Please disregard.
Aug 27 '08 #5
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
Aug 27 '08 #6
balabaster
797 Expert 512MB
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:

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.  
  40.  

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.Binary) 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
  99.  
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.
Aug 27 '08 #7
Plater
7,872 Expert 4TB
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
Aug 27 '08 #8
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.
Aug 27 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Steve Bywaters | last post by:
I have the following error on a page ... I can fix it by making a large-ish block of text (almostr 4k) a little smaller. But what is ASP actually complaining about? Steve Response object...
1
by: inkapyrite | last post by:
Hi all. I'm using ifstream to read from a named pipe but i've encountered an annoying problem. For some reason, the program blocks on reading an ifstream's internal buffer that's only half-filled....
5
by: daniel.shaya | last post by:
I'll try and keep this brief so in a nutshell: I have large distributed java system running on a Windows 2003 server (4cpu 8Gb memory). Periodically the following exceptions occurs in the...
2
by: David Richards | last post by:
Hi, Hopefully someone can help me. I have setup a continuous form that displays customer names and addresses. I have then place a txt box on the form header. Using the onChange event I've setup...
28
by: bwaichu | last post by:
Is it generally better to set-up a buffer (fixed sized array) and read and write to that buffer even if it is larger than what is being written to it? Or is it better to allocate memory and...
26
by: Andrew Poelstra | last post by:
I hacked this together this morning so that I could shift my out-of- space code away from the rest of my logic. I wanted to allow array syntax on my dynamic buffers, so I manually created a struct...
64
by: Philip Potter | last post by:
Hello clc, I have a buffer in a program which I write to. The buffer has write-only, unsigned-char-at-a-time access, and the amount of space required isn't known a priori. Therefore I want the...
70
by: junky_fellow | last post by:
Guys, If main() calls some function func() and that function returns the error (errno), then does it make sense to return that value (errno) from main. (in case main can't proceed further) ? ...
36
by: James Harris | last post by:
Initial issue: read in an arbitrary-length piece of text. Perceived issue: handle variable-length data The code below is a suggestion for implementing a variable length buffer that could be used...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.