Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1089551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:14:22+00:00 2026-05-16T23:14:22+00:00

The following code waits for data over UDP. I have a test function that

  • 0

The following code waits for data over UDP. I have a test function that sends 1000 packets (datagrams?) of 500 bytes each. Each time I run the test function, the receiver gets only the first few dozen packets but drops the rest. I looked at the incoming network data using Wireshark and I see all 1000 packets are actually received, but just don’t make it to may app’s code.

Here is some of the relevant VB.NET 3.5 code:

Private _UdbBuffer As Byte()
Private _ReceiveSocket As Socket
Private _NumReceived As Integer = 0
Private _StopWaitHandle As AutoResetEvent

Private Sub UdpListen()
    _StopWaitHandle = New AutoResetEvent(False)
    _UdpEndPoint = New Net.IPEndPoint(Net.IPAddress.Any, UDP_PORT_NUM)

    _ReceiveSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
    _ReceiveSocket.Bind(_UdpEndPoint)

    ReDim _UdbBuffer(10000)

    While Not _StopRequested
        Dim ir As IAsyncResult = _ReceiveSocket.BeginReceive(_UdbBuffer, 0, 10000, SocketFlags.None, AddressOf UdpReceive, Nothing)

        If Not _StopRequested Then
            Dim waitHandles() As WaitHandle = {_StopWaitHandle, ir.AsyncWaitHandle}
            If (WaitHandle.WaitAny(waitHandles) = 0) Then
                Exit While
            End If
        End If
    End While

    _ReceiveSocket.Close()
End Sub

Private Sub UdpReceive(ByVal ar As IAsyncResult)
    Dim len As Integer
    If ar.IsCompleted Then
        len = _ReceiveSocket.EndReceive(ar)
        Threading.Interlocked.Increment(_NumReceived)
        RaiseStatus("Got " & _NumReceived & " packets")
    End If
End Sub

I am sending the data as follows (not worried about the packet content for now):

For i as UShort = 0 to 999
   Dim b(500) as Byte
   _UdpClient.Send(b, b.Length)       
Next

If I add a small delay after each call to Send, more packets make it through; however since Wireshark says that they were all received anyways, it seems that the problem is in my receive code. I should mention that UdpListen is running on a separate thread.

Any idea why I am dropping packets? I also tried UdpClient.BeginReceive/EndReceive but had the same problem.

A second issue that bothers me is the global nature of the receive buffer when using Sockets and I am not sure if I don’t process incoming packets quickly enough that the buffer will be overwritten. Not sure what to do about that just yet but I am open to suggestions.

Sep 26: Update


Based on the various, somewhat conflicting suggestions from replies to this and other posts, I made some changes to my code. Thanks to all who chimed in various bits; I now get all my packets from dial-up to Fast Ethernet. As you can see, it was my code at fault and not the fact that UDP drops packets (in fact I have not seen more than a tiny percentage of packets being dropped or out of order since my fixes).

Differences:

1) Replaced BeginReceive()/EndReceive() with BeginReceiveFrom()/EndReceiveFrom(). By itself this had no notible effect though.

2) Chaining BeginReceiveFrom() calls instead of waiting for the async handle to set. Not sure if any benefit here.

3) Explicitly set the Socket.ReceiveBufferSize to 500000 which is enough for 1 second worth of my data at Fast Ethernet speed. Turns out this is a different buffer than the one passed to BeginReceiveFrom(). This had the biggest benefit.

4) I also modified my send routine to wait a couple of ms after having sent a certain number of bytes to throttle based on expected bandwidth. This had a big benefit for my receiving code even though Wireshark said all my data still made it across even without this delay.

I did NOT end up using a separate processing thread because, as I understand it, each call to BeginReceiveFrom will invoke my callback on a new worker thread. This means that I can have more than one callback running at the same time. It also means that once I call BeginReceiveFrom I have time to do my stuff (as long as I don’t take too long and exaust the available worker threads).

Private Sub StartUdpListen()
    _UdpEndPoint = New Net.IPEndPoint(Net.IPAddress.Any, UDP_PORT_NUM)
    _ReceiveSocket = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
    _ReceiveSocket.ReceiveBufferSize = 500000
    _ReceiveSocket.Bind(_UdpEndPoint)

    ReDim _Buffer(50000)

    _ReceiveSocket.BeginReceiveFrom(_Buffer, 0, _Buffer.Length, SocketFlags.None, _UdpEndPoint, AddressOf UdpReceive, Nothing)

End Sub

Private Sub UdpReceive(ByVal ar As IAsyncResult)
    Dim len As Integer = _ReceiveSocket.EndReceiveFrom(ar, _UdpEndPoint)
    Threading.Interlocked.Increment(udpreceived)

    Dim receiveBytes As Byte()
    ReDim receiveBytes(len - 1)
    System.Buffer.BlockCopy(_Buffer, 0, receiveBytes, 0, len)

    _ReceiveSocket.BeginReceiveFrom(_Buffer, 0, _UdbBuffer.Length, SocketFlags.None, _UdpEndPoint, AddressOf UdpReceive, Nothing)

    //' At this point, do what we need to do with the data in the receiveBytes buffer
    Trace.WriteLine("count=" & udpreceived)
End Sub

What is not shown above is the error handling and dealing with UDP data being out of order or missing.

I think this handles my issue, but if anybody still sees anything wrong with the above (or something I could do better) I would love to hear about it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:14:23+00:00Added an answer on May 16, 2026 at 11:14 pm

    UDP can drop packets whenever it likes. In this case you could try setting a much larger socket receive buffer at the receiver to mitigate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code at the end of an .each() function that loops
i have the following code that opens a dialogue with a View. $('.bulkEditlink').click(function ()
I have the following Objective C test code in a SenTestCase class. I get
I have the following code: $('#DoButton').click(function (event) { event.preventDefault(); $(input:checked).each(function () { var id
I got a problem, I have this code: $(document).ready(function(){ /* The following code is
I was using the following code to send data asynchronously but I noticed that
Will the following code load data from file into system memory so that access
I have the following html code gogu@yahoo.com wants to be your partner. Do you
Following code iterates through many data-rows, calcs some score per row and then sorts
I have following code: public class readSensorsData extends Activity implements SensorListener { /** Called

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.