简体   繁体   中英

How can I see how many bytes a C# socket has queued to send?

In my C# application, I am sending UDP messages by calling Socket.SendTo potentially up to 10,000 times per second. I know that it is sometimes unable to keep up with how much I am sending. Is there a way to check how much data (in bytes, or number of times I've called SendTo , etc.) it has queued or backlogged to send?

My ideal solution would be to drop the non-essential messages if the socket starts running behind and let the essential messages be queued by the socket, so knowing the socket status before I call SendTo would be quite helpful.

Thanks

The packets could be queued in so many different places it's not really feasible to do this: they could be on the socket, in the IP stack somewhere, in the network interface output queue, etc...

Even if you find a way to query the appropriate queues in the operating system (which will surely not be portable), you won't really solve your problem by doing this. The reason is that unless you are actually sending messages out faster than your network interface can handle, the bottleneck is most likely somewhere on the network, outside the sending computer. Since many network interfaces on general purpose computers these days are 1Gbps, it is very likely that the network interface is able to send out packets as fast as you originate them. The choke point is probably an ethernet switch or a router somewhere, and you won't be able to find out by querying queues when that ethernet switch or router is dropping packets and when it isn't.

The problem with what you want to do is that it's the OS kernel, not your application, that is managing the outgoing queue. And with UDP even less queuing going on, so packets just get dropped if needed.

Your best bet is netstat -s on the command line to see protocol statistics and packet drop counts (Windows probably has some fancy API to query the same from an app, but I'm not aware of it).

Find an acceptable message rate your host and network can sustain, and switch to a "lean" output when that is reached/exceeded. This requires some bookkeeping, but could easily be accomplished with a ring-buffer of timestamps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM