PilawyerDev
PilawyerDev

Reputation: 271

Cancel pending recv?

Hi I'm working on a networking project. I've a socket that is listening incoming data. Now I want to archive this: Socket will receive only 100 packets. And there is 3-4 clients. They are sending random data packets infinitely. I'll receive 100 packets and later I'll process them. After process I'll re-start receiving. But at this time there are some pending send() >> recv() operations. Now I want to cancel/discard pending recv operations. I think we'll recv datas and we'll not process them. Any other suggestions? (sorry for bad question composition)

Upvotes: 1

Views: 2110

Answers (3)

Arty
Arty

Reputation: 763

I would go with non-blocking sockets + cancellation socket. You'll have to read into dedicated incremental buffer (as recv() may not receive all the data expected at once - this would be the case if you can only process full messages) and return to select()/poll() in your loop, where you can safely sit and wait for:

  • next data
  • next connection
  • cancellation event from a cancellation socket, to which your other thread will send a cancellation signal (some trivial send()).

UPD: the trivial event may be the number of the socket in the array or its handle - something to identify which one you'd like to cancel.

Upvotes: 1

tristan
tristan

Reputation: 4322

You can use select() or poll() loops. you can use signal. recv() will return on receiving a signal so you can send a signal from another task to the task that blocks on recv(). But you need to make sure you don't specify SA_RESTART (see http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html)

Read http://en.wikipedia.org/wiki/Asynchronous_I/O for more details

Upvotes: 1

usr
usr

Reputation: 171246

Shutdown and close the connection. That will cancel everything immediately.

Better yet, rearchitect your application and network protocol so that you can reliably tell how much data to receive.

On Windows you can cancel outstanding receives using CancelIO, but that might result in lost data if the receive just happened to read something.

Upvotes: 4

Related Questions