send with timeout socket

Steve Holden steve at holdenweb.com
Fri Sep 22 14:41:41 CEST 2006


Stéphane Ninin wrote:
>   Hello,
> 
> I have a few questions regarding sockets with timeouts.
> 
> Assuming you set a timeout t on a socket s and then call:
> 
> 
> 1) s.sendall
> Is the socket.timeout exception thrown when
> not the data was sent in the given time t 
> or if nothing was sent ?
> 
> 2) Similar question for s.send:
> Is the socket.timeout exception thrown when 
> nothing was sent or ... ?
> 
> 
>   What I am actually trying to do is this:
> 
> I have a thread which uses a socket to communicate with a socket server,
> the socket sends data to the server, but it shouldnot block on the send,
> so I want to do something like this:
> 
>     def sendall(self,data):
>         while data:
>             n = self.send(data)
>             data = data[n:]
>     	    	 try:
>                self.request.send(data)
>             except socket.timeout, e:
>                if self.isTerminated():
>                   return
> 
> but I am not sure this would work the way I want.
> 
It wouldn't even compile, as your indentation is shot.

Plus, if the first send attempt (the one before the try) sends all the 
data you then try to send an empty string, which seems a little weird: I 
don't see the point of the try/except.

> (self.isTerminated just checks is some event 
> has been set by another thread)
> 
> 
>  Thanks for comments/suggestions/answers,
> 
>  
Sending sockets will usually only block when the sliding window is full 
(the sender has sent as much data as the remote receiver has indicated 
it can safely receive without loss) and no acknowledgment has been 
received from the remote receiver.

Rather than a timeout it would seem sensible, if you don't want the 
sending socket to block, to use a non-blocking socket. That way you get 
a socket.error if a send would otherwise block.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list