lily
lily

Reputation: 565

how to properly deal with send/write with a non-blocking socket?

I have a socket which is used to receive and also send packets. And the pseudo codes are:

   setnonblock(fd);
   add_event(event_base, recv_ev);
   while("I have packets to write"){
      send(fd, packet);
      ....
   }

   ....

now the issue is, since fd is non-blocking, send(fd) many return before it finish sending packets. but I hope it can send the packet successfully before the program runs to the next step, or register an event for it. But if I register an event for it, the event may be triggered frequently even if there are no packets available (note the packets are not from recv() in the pseudo code ,but from somewhere else)

then how to deal with it?

Upvotes: 0

Views: 251

Answers (1)

user207421
user207421

Reputation: 310884

The is all back to front. Sockets are almost always writeable. So you should:

  • send when you have data to send
  • call each send in a loop until t either completed or returns zero
  • if it returned zero, then select on writeability, and resume sending when it fires, and then cease selecting on writeability.

Upvotes: 1

Related Questions