Example using the select module

Fredrik Lundh fredrik at pythonware.com
Mon Oct 11 14:21:48 EDT 1999


James Turney <jtt at hnc.com> wrote:
> Does anybody have and example using the select module with sockets.

very schematic (read on to find out why):

s = socket.socket(...)

# switch to non-blocking mode (only
# needed if you want to to non-block-
# ing connects; see below).
s.setblocking(0)

...bind, connect, listen, whatever...

r, w, e = select.select([s], [s], [s], timeout)

if r:
    # after a "listen", indicates that
    # "accept" will succeed
   
    # or data is available -- "recv"
    # will succeed

    # or connection is closed/reset/
    # terminated (recv will return an
    # empty string)

if w:

    # after a non-blocking "connect",
    # indicates that connection succeeded

    # or data can be written ("send"
    # will succeed)

if e:

    # after a non-blocking "connect",
    # indicates that connection failed

but your time is probably better spent by looking
at the asyncore framework, which keeps track of
all this for you:
http://www.python.org/doc/current/lib/module-asyncore.html

(if you still want an example, reading the asyncore
sources if of course your best bet)

</F>

coming soon:
http://www.pythonware.com/people/fredrik/librarybook.htm
(yes, it covers sockets, select, and asyncore too!)





More information about the Python-list mailing list