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.
56 from errno
import EALREADY
, EINPROGRESS
, EWOULDBLOCK
, ECONNRESET
, \
57 ENOTCONN
, ESHUTDOWN
, EINTR
, EISCONN
64 class ExitNow(exceptions
.Exception):
69 obj
.handle_read_event()
77 obj
.handle_write_event()
83 def readwrite(obj
, flags
):
85 if flags
& select
.POLLIN
:
86 obj
.handle_read_event()
87 if flags
& select
.POLLOUT
:
88 obj
.handle_write_event()
94 def poll(timeout
=0.0, map=None):
98 r
= []; w
= []; e
= []
99 for fd
, obj
in map.items():
104 if [] == r
== w
== e
:
108 r
, w
, e
= select
.select(r
, w
, e
, timeout
)
109 except select
.error
, err
:
127 def poll2(timeout
=0.0, map=None):
131 if timeout
is not None:
132 # timeout is in milliseconds
133 timeout
= int(timeout
*1000)
136 for fd
, obj
in map.items():
141 flags
= flags | poll
.POLLOUT
143 l
.append((fd
, flags
))
144 r
= poll
.poll(l
, timeout
)
149 readwrite(obj
, flags
)
151 def poll3(timeout
=0.0, map=None):
152 # Use the poll() support added to the select module in Python 2.0
155 if timeout
is not None:
156 # timeout is in milliseconds
157 timeout
= int(timeout
*1000)
158 pollster
= select
.poll()
160 for fd
, obj
in map.items():
163 flags
= select
.POLLIN
165 flags
= flags | select
.POLLOUT
167 pollster
.register(fd
, flags
)
169 r
= pollster
.poll(timeout
)
170 except select
.error
, err
:
178 readwrite(obj
, flags
)
180 def loop(timeout
=30.0, use_poll
=0, map=None):
185 if hasattr(select
, 'poll'):
193 poll_fun(timeout
, map)
203 def __init__(self
, sock
=None, map=None):
205 self
.set_socket(sock
, map)
206 # I think it should inherit this anyway
207 self
.socket
.setblocking(0)
209 # XXX Does the constructor require that the socket passed
212 self
.addr
= sock
.getpeername()
214 # The addr isn't crucial
220 status
= [self
.__class
__.__module
__+"."+self
.__class
__.__name
__]
221 if self
.accepting
and self
.addr
:
222 status
.append('listening')
224 status
.append('connected')
225 if self
.addr
is not None:
227 status
.append('%s:%d' % self
.addr
)
229 status
.append(repr(self
.addr
))
230 return '<%s at %#x>' % (' '.join(status
), id(self
))
232 def add_channel(self
, map=None):
233 #self.log_info('adding channel %s' % self)
236 map[self
._fileno
] = self
238 def del_channel(self
, map=None):
243 #self.log_info('closing channel %d:%s' % (fd, self))
246 def create_socket(self
, family
, type):
247 self
.family_and_type
= family
, type
248 self
.socket
= socket
.socket(family
, type)
249 self
.socket
.setblocking(0)
250 self
._fileno
= self
.socket
.fileno()
253 def set_socket(self
, sock
, map=None):
255 ## self.__dict__['socket'] = sock
256 self
._fileno
= sock
.fileno()
257 self
.add_channel(map)
259 def set_reuse_addr(self
):
260 # try to re-use a server port if possible
262 self
.socket
.setsockopt(
263 socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
,
264 self
.socket
.getsockopt(socket
.SOL_SOCKET
,
265 socket
.SO_REUSEADDR
) |
1
270 # ==================================================
271 # predicates for select()
272 # these are used as filters for the lists of sockets
273 # to pass to select().
274 # ==================================================
280 # The macintosh will select a listening socket for
281 # write if you let it. What might this mean?
283 return not self
.accepting
288 # ==================================================
289 # socket object methods.
290 # ==================================================
292 def listen(self
, num
):
294 if os
.name
== 'nt' and num
> 5:
296 return self
.socket
.listen(num
)
298 def bind(self
, addr
):
300 return self
.socket
.bind(addr
)
302 def connect(self
, address
):
304 err
= self
.socket
.connect_ex(address
)
305 # XXX Should interpret Winsock return values
306 if err
in (EINPROGRESS
, EALREADY
, EWOULDBLOCK
):
308 if err
in (0, EISCONN
):
311 self
.handle_connect()
313 raise socket
.error
, err
316 # XXX can return either an address pair or None
318 conn
, addr
= self
.socket
.accept()
320 except socket
.error
, why
:
321 if why
[0] == EWOULDBLOCK
:
324 raise socket
.error
, why
326 def send(self
, data
):
328 result
= self
.socket
.send(data
)
330 except socket
.error
, why
:
331 if why
[0] == EWOULDBLOCK
:
334 raise socket
.error
, why
337 def recv(self
, buffer_size
):
339 data
= self
.socket
.recv(buffer_size
)
341 # a closed connection is indicated by signaling
342 # a read condition, and having recv() return 0.
347 except socket
.error
, why
:
348 # winsock sometimes throws ENOTCONN
349 if why
[0] in [ECONNRESET
, ENOTCONN
, ESHUTDOWN
]:
353 raise socket
.error
, why
359 # cheap inheritance, used to pass all other attribute
360 # references to the underlying socket object.
361 def __getattr__(self
, attr
):
362 return getattr(self
.socket
, attr
)
364 # log and log_info may be overridden to provide more sophisticated
365 # logging and warning methods. In general, log is for 'hit' logging
366 # and 'log_info' is for informational, warning and error logging.
368 def log(self
, message
):
369 sys
.stderr
.write('log: %s\n' % str(message
))
371 def log_info(self
, message
, type='info'):
372 if __debug__
or type != 'info':
373 print '%s: %s' % (type, message
)
375 def handle_read_event(self
):
377 # for an accepting socket, getting a read implies
378 # that we are connected
379 if not self
.connected
:
382 elif not self
.connected
:
383 self
.handle_connect()
389 def handle_write_event(self
):
390 # getting a write implies that we are connected
391 if not self
.connected
:
392 self
.handle_connect()
396 def handle_expt_event(self
):
399 def handle_error(self
):
400 nil
, t
, v
, tbinfo
= compact_traceback()
402 # sometimes a user repr method will crash.
404 self_repr
= repr(self
)
406 self_repr
= '<__repr__(self) failed for object at %0x>' % id(self
)
409 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
419 def handle_expt(self
):
420 self
.log_info('unhandled exception', 'warning')
422 def handle_read(self
):
423 self
.log_info('unhandled read event', 'warning')
425 def handle_write(self
):
426 self
.log_info('unhandled write event', 'warning')
428 def handle_connect(self
):
429 self
.log_info('unhandled connect event', 'warning')
431 def handle_accept(self
):
432 self
.log_info('unhandled accept event', 'warning')
434 def handle_close(self
):
435 self
.log_info('unhandled close event', 'warning')
438 # ---------------------------------------------------------------------------
439 # adds simple buffered output capability, useful for simple clients.
440 # [for more sophisticated usage use asynchat.async_chat]
441 # ---------------------------------------------------------------------------
443 class dispatcher_with_send(dispatcher
):
445 def __init__(self
, sock
=None):
446 dispatcher
.__init
__(self
, sock
)
449 def initiate_send(self
):
451 num_sent
= dispatcher
.send(self
, self
.out_buffer
[:512])
452 self
.out_buffer
= self
.out_buffer
[num_sent
:]
454 def handle_write(self
):
458 return (not self
.connected
) or len(self
.out_buffer
)
460 def send(self
, data
):
462 self
.log_info('sending %s' % repr(data
))
463 self
.out_buffer
= self
.out_buffer
+ data
466 # ---------------------------------------------------------------------------
467 # used for debugging.
468 # ---------------------------------------------------------------------------
470 def compact_traceback():
471 t
, v
, tb
= sys
.exc_info()
473 assert tb
# Must have a traceback
476 tb
.tb_frame
.f_code
.co_filename
,
477 tb
.tb_frame
.f_code
.co_name
,
485 file, function
, line
= tbinfo
[-1]
486 info
= ' '.join(['[%s|%s|%s]' % x
for x
in tbinfo
])
487 return (file, function
, line
), t
, v
, info
489 def close_all(map=None):
492 for x
in map.values():
496 # Asynchronous File I/O:
498 # After a little research (reading man pages on various unixen, and
499 # digging through the linux kernel), I've determined that select()
500 # isn't meant for doing doing asynchronous file i/o.
501 # Heartening, though - reading linux/mm/filemap.c shows that linux
502 # supports asynchronous read-ahead. So _MOST_ of the time, the data
503 # will be sitting in memory for us already when we go to read it.
505 # What other OS's (besides NT) support async file i/o? [VMS?]
507 # Regardless, this is useful for pipes, and stdin/stdout...
509 if os
.name
== 'posix':
513 # here we override just enough to make a file
514 # look like a socket for the purposes of asyncore.
516 def __init__(self
, fd
):
519 def recv(self
, *args
):
520 return os
.read(self
.fd
, *args
)
522 def send(self
, *args
):
523 return os
.write(self
.fd
, *args
)
529 return os
.close(self
.fd
)
534 class file_dispatcher(dispatcher
):
536 def __init__(self
, fd
):
537 dispatcher
.__init
__(self
)
539 # set it to non-blocking mode
540 flags
= fcntl
.fcntl(fd
, fcntl
.F_GETFL
, 0)
541 flags
= flags | os
.O_NONBLOCK
542 fcntl
.fcntl(fd
, fcntl
.F_SETFL
, flags
)
545 def set_file(self
, fd
):
547 self
.socket
= file_wrapper(fd
)