简体   繁体   中英

Is it possible to read the number of bytes buffered for a TCP write socket?

I have an app that uses the civetweb (formerly mongoose) HTTP server library to create an MJPEG stream. Works fine when my MJPEG settings match the bandwidth profile of the network the clients are connecting from, but occasionally we have a low bandwidth connection that I'd like to accommodate by dropping frames.

Right now when I call mg_write() , the mongoose library calls send() like this:

send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);

What I'd like to do is check the outgoing buffer of the socket, and if it's full, skip a frame. Is there any way to check this at the application level?

EDIT: Just a side note for MJPEG folks, these TCP buffers are pretty large and what I actually ended up measuring was simply if there were any bytes present in the buffer at all. If there were more than zero I skipped a frame.

You can use ioctl for this on Linux (and similar interfaces on other systems):

#include <linux/sockios.h>

size_t sb_sz = sizeof(sock_buffer_size);
ioctl(sock, SIOCOUTQ, &bytes_in_queue);
getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sock_buffer_size, &sb_sz);
size_t bytes_available = sock_buffer_size - bytes_in_queue;

Note that it still does not give you 100% guarantee that the write will succeed in full, but it gives you pretty good chance of it.

What I'd like to do is check the outgoing buffer of the socket, and if it's full, skip a frame. Is there any way to check this at the application level?

Sure, call select () and see if the socket selects as ready-for-write. If it doesn't, that means the socket's outgoing buffer is full. (You can use select()'s timeout parameter to force the select() call to return immediately, if you don't want it to block until a socket is ready to read/write/etc)

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