sockets: How to know when your data is sent

Richie Hindle richie at entrian.com
Wed Nov 10 10:31:51 EST 2004


[Marc]
> When I use the send function, it will
> happily send a buffer of a megabyte and more in one shot. But
> of course, the data is still in the network buffer... Meaning
> you can't disconnect for awhile (but for how long...). The
> problem is, how can I know when it's done? Is there a way to
> be notified when the data has truly been sent?

[Grant]
> Under Linux, there is no way to tell.  IIRC, there's no way to
> tell under BSD either. [...]
> The way to tell that data has been sent is to use an
> application-level protocol that acknowleges the data transferr.

If you want to ensure that all the data has been sent before *closing* the
socket, which sounds like Marc's requirement, you can use
setsockopt(SO_LINGER):

       SO_LINGER
              Sets  or gets the SO_LINGER option. The argument is
              a linger structure.

              struct linger {
                  int   l_onoff;    /* linger active */
                  int   l_linger;   /* how many seconds to linger for */
              };

              When enabled, a close(2) or  shutdown(2)  will  not
              return  until  all  queued  messages for the socket
              have been successfully sent or the  linger  timeout
              has been reached. Otherwise, the call returns imme­
              diately and the closing is done in the  background.
              When  the  socket  is closed as part of exit(2), it
              always lingers in the background.

(from the GNU manpages).  I don't believe that's true for shutdown() on
all platforms, but I do believe it's true for close() / closesocket().
Calling it from Python is a bit of a chore involving the struct module,
and is left as an exercise for the reader.  8-)

-- 
Richie Hindle
richie at entrian.com




More information about the Python-list mailing list