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 1616
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.
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: -
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.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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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....
|
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...
|
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...
|
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...
|
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...
|
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...
|
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) ?
...
|
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...
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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,...
|
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...
|
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...
|
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...
|
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...
|
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,...
|
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...
| |