views:

223

answers:

1

Here's the code on the sending side of my sockets:

    Private Sub Send(ByRef Buffer() As Byte)
        Dim obj_StateObject As New StateObject
        obj_StateObject.WorkSocket = m_tmpSocket
        m_tmpSocket.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnClientSendComplete), obj_StateObject)
    End Sub

    Private Sub OnClientSendComplete(ByVal ar As IAsyncResult)
        Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
        Dim obj_Socket As Socket = obj_SocketState.WorkSocket
    End Sub

Here's the receiving code:

    Private Sub OnServerDataArrival(ByVal ar As IAsyncResult)
        Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
        Dim obj_Socket As Socket = obj_SocketState.WorkSocket
        Dim BytesRead As Integer = obj_Socket.EndReceive(ar)

        If (BytesRead > 0) Then
            Dim TempLength As Integer = BitConverter.ToInt32(obj_SocketState.Buffer, 0) - 4
            Dim TempBuffer(TempLength - 1) As Byte
            Array.Copy(obj_SocketState.Buffer, 4, TempBuffer, 0, TempLength)
            RaiseEvent ServerDataArrival(TMP_ID, TempBuffer)
        End If

        obj_Socket.BeginReceive(obj_SocketState.Buffer, 0, obj_SocketState.BufferSize, 0, New AsyncCallback(AddressOf OnServerDataArrival), obj_SocketState)
    End Sub

I can send and receive data just fine usually. For instance, I can send a 10 byte buffer across with a button click and there are no problems.

However, if I set that button to call a function that will loop the sending of the 10 byte buffer 10 times, I will not receive about 8 of the buffers on average.

What is causing this? The sending code is executed 10 times, but the OnServerDataArrival function is only executed 2 times.

+1  A: 

It is not clear from the code you've provided, but my guess is that you are transmitting the data using TCP (as opposed to UDP). If this is true, you shouldn't expect the send count to match the receive count. If you want that behavior, use UDP instead of TCP.

When using TCP, the data is typically buffered on the send side until a "sufficient" amount of data is ready to be sent. This usually helps improve the overall efficiency of the transmission, especially when sending messages as small as 10 bytes at a time. On the receive side, each read of the TCP socket reads all of the data from the socket's receive buffer up to the size of the buffer you provide. So if 8 of your 10 byte "messages" have been received, the next read from the socket will pull all that data into your buffer (providing it's big enough). You will need to parse your buffer to extract each message from the stream of bytes. Sending the size of the message, as you appear to be doing, will help you do this.

Matt Davis
Thanks... this helps tremendously.
CowKingDeluxe