2 # Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
3 # Author: Sam Rushing <rushing@nightmare.com>
5 # ======================================================================
6 # Copyright 1996 by Sam Rushing
10 # Permission to use, copy, modify, and distribute this software and
11 # its documentation for any purpose and without fee is hereby
12 # granted, provided that the above copyright notice appear in all
13 # copies and that both that copyright notice and this permission
14 # notice appear in supporting documentation, and that the name of Sam
15 # Rushing not be used in advertising or publicity pertaining to
16 # distribution of the software without specific, written prior
19 # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
20 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
21 # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
22 # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
23 # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
24 # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
25 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 # ======================================================================
28 """Basic infrastructure for asynchronous socket service clients and servers.
30 There are only two ways to have a program on a single processor do "more
31 than one thing at a time". Multi-threaded programming is the simplest and
32 most popular way to do it, but there is another very different technique,
33 that lets you have nearly all the advantages of multi-threading, without
34 actually using multiple threads. it's really only practical if your program
35 is largely I/O bound. If your program is CPU bound, then pre-emptive
36 scheduled threads are probably what you really need. Network servers are
37 rarely CPU-bound, however.
39 If your operating system supports the select() system call in its I/O
40 library (and nearly all do), then you can use it to juggle multiple
41 communication channels at once; doing other work while your I/O is taking
42 place in the "background." Although this strategy can seem strange and
43 complex, especially at first, it is in many ways easier to understand and
44 control than multi-threaded programming. The module documented here solves
45 many of the difficult problems for you, making the task of building
46 sophisticated high-performance network servers and clients a snap.
55 from errno
import EALREADY
, EINPROGRESS
, EWOULDBLOCK
, ECONNRESET
, \
56 ENOTCONN
, ESHUTDOWN
, EINTR
, EISCONN
63 class ExitNow (exceptions
.Exception):
68 def poll (timeout
=0.0, map=None):
72 r
= []; w
= []; e
= []
73 for fd
, obj
in map.items():
79 r
,w
,e
= select
.select (r
,w
,e
, timeout
)
80 except select
.error
, err
:
94 obj
.handle_read_event()
107 obj
.handle_write_event()
113 def poll2 (timeout
=0.0, map=None):
117 if timeout
is not None:
118 # timeout is in milliseconds
119 timeout
= int(timeout
*1000)
122 for fd
, obj
in map.items():
127 flags
= flags | poll
.POLLOUT
129 l
.append ((fd
, flags
))
130 r
= poll
.poll (l
, timeout
)
138 if (flags
& poll
.POLLIN
):
139 obj
.handle_read_event()
140 if (flags
& poll
.POLLOUT
):
141 obj
.handle_write_event()
147 def poll3 (timeout
=0.0, map=None):
148 # Use the poll() support added to the select module in Python 2.0
151 if timeout
is not None:
152 # timeout is in milliseconds
153 timeout
= int(timeout
*1000)
154 pollster
= select
.poll()
156 for fd
, obj
in map.items():
159 flags
= select
.POLLIN
161 flags
= flags | select
.POLLOUT
163 pollster
.register(fd
, flags
)
165 r
= pollster
.poll (timeout
)
166 except select
.error
, err
:
177 if (flags
& select
.POLLIN
):
178 obj
.handle_read_event()
179 if (flags
& select
.POLLOUT
):
180 obj
.handle_write_event()
186 def loop (timeout
=30.0, use_poll
=0, map=None):
192 if hasattr (select
, 'poll'):
200 poll_fun (timeout
, map)
209 def __init__ (self
, sock
=None, map=None):
211 self
.set_socket (sock
, map)
212 # I think it should inherit this anyway
213 self
.socket
.setblocking (0)
215 # XXX Does the constructor require that the socket passed
218 self
.addr
= sock
.getpeername()
220 # The addr isn't crucial
226 status
= [self
.__class
__.__module
__+"."+self
.__class
__.__name
__]
227 if self
.accepting
and self
.addr
:
228 status
.append ('listening')
230 status
.append ('connected')
231 if self
.addr
is not None:
233 status
.append ('%s:%d' % self
.addr
)
235 status
.append (repr(self
.addr
))
236 return '<%s at %#x>' % (' '.join (status
), id (self
))
238 def add_channel (self
, map=None):
239 #self.log_info ('adding channel %s' % self)
242 map [self
._fileno
] = self
244 def del_channel (self
, map=None):
249 #self.log_info ('closing channel %d:%s' % (fd, self))
252 def create_socket (self
, family
, type):
253 self
.family_and_type
= family
, type
254 self
.socket
= socket
.socket (family
, type)
255 self
.socket
.setblocking(0)
256 self
._fileno
= self
.socket
.fileno()
259 def set_socket (self
, sock
, map=None):
261 ## self.__dict__['socket'] = sock
262 self
._fileno
= sock
.fileno()
263 self
.add_channel (map)
265 def set_reuse_addr (self
):
266 # try to re-use a server port if possible
268 self
.socket
.setsockopt (
269 socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
,
270 self
.socket
.getsockopt (socket
.SOL_SOCKET
,
271 socket
.SO_REUSEADDR
) |
1
276 # ==================================================
277 # predicates for select()
278 # these are used as filters for the lists of sockets
279 # to pass to select().
280 # ==================================================
286 # The macintosh will select a listening socket for
287 # write if you let it. What might this mean?
289 return not self
.accepting
294 # ==================================================
295 # socket object methods.
296 # ==================================================
298 def listen (self
, num
):
300 if os
.name
== 'nt' and num
> 5:
302 return self
.socket
.listen (num
)
304 def bind (self
, addr
):
306 return self
.socket
.bind (addr
)
308 def connect (self
, address
):
310 err
= self
.socket
.connect_ex(address
)
311 if err
in (EINPROGRESS
, EALREADY
, EWOULDBLOCK
):
313 if err
in (0, EISCONN
):
316 self
.handle_connect()
318 raise socket
.error
, err
322 conn
, addr
= self
.socket
.accept()
324 except socket
.error
, why
:
325 if why
[0] == EWOULDBLOCK
:
328 raise socket
.error
, why
330 def send (self
, data
):
332 result
= self
.socket
.send (data
)
334 except socket
.error
, why
:
335 if why
[0] == EWOULDBLOCK
:
338 raise socket
.error
, why
341 def recv (self
, buffer_size
):
343 data
= self
.socket
.recv (buffer_size
)
345 # a closed connection is indicated by signaling
346 # a read condition, and having recv() return 0.
351 except socket
.error
, why
:
352 # winsock sometimes throws ENOTCONN
353 if why
[0] in [ECONNRESET
, ENOTCONN
, ESHUTDOWN
]:
357 raise socket
.error
, why
363 # cheap inheritance, used to pass all other attribute
364 # references to the underlying socket object.
365 def __getattr__ (self
, attr
):
366 return getattr (self
.socket
, attr
)
368 # log and log_info maybe overriden to provide more sophisitcated
369 # logging and warning methods. In general, log is for 'hit' logging
370 # and 'log_info' is for informational, warning and error logging.
372 def log (self
, message
):
373 sys
.stderr
.write ('log: %s\n' % str(message
))
375 def log_info (self
, message
, type='info'):
376 if __debug__
or type != 'info':
377 print '%s: %s' % (type, message
)
379 def handle_read_event (self
):
381 # for an accepting socket, getting a read implies
382 # that we are connected
383 if not self
.connected
:
386 elif not self
.connected
:
387 self
.handle_connect()
393 def handle_write_event (self
):
394 # getting a write implies that we are connected
395 if not self
.connected
:
396 self
.handle_connect()
400 def handle_expt_event (self
):
403 def handle_error (self
):
404 nil
, t
, v
, tbinfo
= compact_traceback()
406 # sometimes a user repr method will crash.
408 self_repr
= repr (self
)
410 self_repr
= '<__repr__ (self) failed for object at %0x>' % id(self
)
413 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
423 def handle_expt (self
):
424 self
.log_info ('unhandled exception', 'warning')
426 def handle_read (self
):
427 self
.log_info ('unhandled read event', 'warning')
429 def handle_write (self
):
430 self
.log_info ('unhandled write event', 'warning')
432 def handle_connect (self
):
433 self
.log_info ('unhandled connect event', 'warning')
435 def handle_accept (self
):
436 self
.log_info ('unhandled accept event', 'warning')
438 def handle_close (self
):
439 self
.log_info ('unhandled close event', 'warning')
442 # ---------------------------------------------------------------------------
443 # adds simple buffered output capability, useful for simple clients.
444 # [for more sophisticated usage use asynchat.async_chat]
445 # ---------------------------------------------------------------------------
447 class dispatcher_with_send (dispatcher
):
448 def __init__ (self
, sock
=None):
449 dispatcher
.__init
__ (self
, sock
)
452 def initiate_send (self
):
454 num_sent
= dispatcher
.send (self
, self
.out_buffer
[:512])
455 self
.out_buffer
= self
.out_buffer
[num_sent
:]
457 def handle_write (self
):
461 return (not self
.connected
) or len(self
.out_buffer
)
463 def send (self
, data
):
465 self
.log_info ('sending %s' % repr(data
))
466 self
.out_buffer
= self
.out_buffer
+ data
469 # ---------------------------------------------------------------------------
470 # used for debugging.
471 # ---------------------------------------------------------------------------
473 def compact_traceback ():
474 t
,v
,tb
= sys
.exc_info()
478 tb
.tb_frame
.f_code
.co_filename
,
479 tb
.tb_frame
.f_code
.co_name
,
489 file, function
, line
= tbinfo
[-1]
490 info
= '[' + '] ['.join(map(lambda x
: '|'.join(x
), tbinfo
)) + ']'
491 return (file, function
, line
), t
, v
, info
493 def close_all (map=None):
496 for x
in map.values():
500 # Asynchronous File I/O:
502 # After a little research (reading man pages on various unixen, and
503 # digging through the linux kernel), I've determined that select()
504 # isn't meant for doing doing asynchronous file i/o.
505 # Heartening, though - reading linux/mm/filemap.c shows that linux
506 # supports asynchronous read-ahead. So _MOST_ of the time, the data
507 # will be sitting in memory for us already when we go to read it.
509 # What other OS's (besides NT) support async file i/o? [VMS?]
511 # Regardless, this is useful for pipes, and stdin/stdout...
514 if os
.name
== 'posix':
518 # here we override just enough to make a file
519 # look like a socket for the purposes of asyncore.
520 def __init__ (self
, fd
):
523 def recv (self
, *args
):
524 return apply (os
.read
, (self
.fd
,)+args
)
526 def send (self
, *args
):
527 return apply (os
.write
, (self
.fd
,)+args
)
533 return os
.close (self
.fd
)
538 class file_dispatcher (dispatcher
):
539 def __init__ (self
, fd
):
540 dispatcher
.__init
__ (self
)
542 # set it to non-blocking mode
543 flags
= fcntl
.fcntl (fd
, fcntl
.F_GETFL
, 0)
544 flags
= flags | os
.O_NONBLOCK
545 fcntl
.fcntl (fd
, fcntl
.F_SETFL
, flags
)
548 def set_file (self
, fd
):
550 self
.socket
= file_wrapper (fd
)