c++ - how can i get the number of bytes available to read on async socket on linux? -


i have simple tcp/ip server written in c++ on linux. i'm using asynchronous sockets , epoll. possible find out how many bytes available reading, when epollin event?

from man 7 tcp:

int value; error = ioctl(sock, fionread, &value); 

or alternatively siocinq, synonym of fionread.

anyway, i'd recommend use recv in non-blocking mode in loop until returns ewouldblock.

update:

from comments below think not appropriate solution problem.

imagine header 8 bytes , receive 4; poll/select return epollin, check fionread, see header not yet complete , wayt more bytes. these bytes never arrive, keep on getting epollin on every call poll/select , have no-op busy-loop. is, poll/select level-triggered. not edge triggered function solves problem either.

at end far better doing bit of work, adding buffer per connection, , queuing bytes until have enough. not difficult seems , works far better. example, that:

struct connectiondata {     int sck;     std::vector<uint8_t> buffer;     size_t offset, pending; };  void onpollin(connectiondata *d) {     int res = recv(d->sck, d->buffer.data() + offset, d->pending);     if (res < 0)          handle_error();     d->offset += res;     d->pending -= res;      if (d->pending == 0)         dosomethinguseful(d); } 

and whenever want number of bytes:

void preparetorecv(connectiondata *d, size_t size) {     d->buffer.resize(size);     d->offset = 0;     d->pending = size; } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -