blob: 5175002a3169002a9f225be4b2ca60431385f2ce [file] [log] [blame]
Fred Drake526a1822000-09-11 04:00:46 +00001# -*- Mode: Python -*-
Tim Peters146965a2001-01-14 18:09:23 +00002# Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp
Fred Drake526a1822000-09-11 04:00:46 +00003# Author: Sam Rushing <rushing@nightmare.com>
Guido van Rossum0039d7b1999-01-12 20:19:27 +00004
5# ======================================================================
6# Copyright 1996 by Sam Rushing
Tim Peters146965a2001-01-14 18:09:23 +00007#
Guido van Rossum0039d7b1999-01-12 20:19:27 +00008# All Rights Reserved
Tim Peters146965a2001-01-14 18:09:23 +00009#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000010# 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
17# permission.
Tim Peters146965a2001-01-14 18:09:23 +000018#
Guido van Rossum0039d7b1999-01-12 20:19:27 +000019# 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# ======================================================================
27
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000028"""Basic infrastructure for asynchronous socket service clients and servers.
29
30There are only two ways to have a program on a single processor do "more
Tim Peters146965a2001-01-14 18:09:23 +000031than one thing at a time". Multi-threaded programming is the simplest and
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000032most popular way to do it, but there is another very different technique,
33that lets you have nearly all the advantages of multi-threading, without
34actually using multiple threads. it's really only practical if your program
35is largely I/O bound. If your program is CPU bound, then pre-emptive
36scheduled threads are probably what you really need. Network servers are
Tim Peters146965a2001-01-14 18:09:23 +000037rarely CPU-bound, however.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000038
Tim Peters146965a2001-01-14 18:09:23 +000039If your operating system supports the select() system call in its I/O
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000040library (and nearly all do), then you can use it to juggle multiple
41communication channels at once; doing other work while your I/O is taking
42place in the "background." Although this strategy can seem strange and
43complex, especially at first, it is in many ways easier to understand and
44control than multi-threaded programming. The module documented here solves
45many of the difficult problems for you, making the task of building
Tim Peters146965a2001-01-14 18:09:23 +000046sophisticated high-performance network servers and clients a snap.
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +000047"""
48
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000049import exceptions
Guido van Rossum0039d7b1999-01-12 20:19:27 +000050import select
51import socket
Guido van Rossum0039d7b1999-01-12 20:19:27 +000052import sys
Jeremy Hylton12e73bb2001-04-20 19:04:55 +000053import types
Guido van Rossum0039d7b1999-01-12 20:19:27 +000054
55import os
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000056from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Tim Peters7c005af2001-08-20 21:48:00 +000057 ENOTCONN, ESHUTDOWN
Guido van Rossum0039d7b1999-01-12 20:19:27 +000058
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000059try:
Fred Drake526a1822000-09-11 04:00:46 +000060 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000061except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000062 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000063
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000064class ExitNow (exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000065 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000066
67DEBUG = 0
68
69def poll (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000070 global DEBUG
71 if map is None:
72 map = socket_map
73 if map:
74 r = []; w = []; e = []
75 for fd, obj in map.items():
76 if obj.readable():
77 r.append (fd)
78 if obj.writable():
79 w.append (fd)
80 r,w,e = select.select (r,w,e, timeout)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000081
Fred Drake526a1822000-09-11 04:00:46 +000082 if DEBUG:
83 print r,w,e
Guido van Rossum0039d7b1999-01-12 20:19:27 +000084
Fred Drake526a1822000-09-11 04:00:46 +000085 for fd in r:
86 try:
87 obj = map[fd]
88 try:
89 obj.handle_read_event()
90 except ExitNow:
91 raise ExitNow
92 except:
93 obj.handle_error()
94 except KeyError:
95 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +000096
Fred Drake526a1822000-09-11 04:00:46 +000097 for fd in w:
98 try:
99 obj = map[fd]
100 try:
101 obj.handle_write_event()
102 except ExitNow:
103 raise ExitNow
104 except:
105 obj.handle_error()
106 except KeyError:
107 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000108
109def poll2 (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000110 import poll
111 if map is None:
112 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000113 if timeout is not None:
114 # timeout is in milliseconds
115 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000116 if map:
117 l = []
118 for fd, obj in map.items():
119 flags = 0
120 if obj.readable():
121 flags = poll.POLLIN
122 if obj.writable():
123 flags = flags | poll.POLLOUT
124 if flags:
125 l.append ((fd, flags))
126 r = poll.poll (l, timeout)
127 for fd, flags in r:
128 try:
129 obj = map[fd]
130 try:
131 if (flags & poll.POLLIN):
132 obj.handle_read_event()
133 if (flags & poll.POLLOUT):
134 obj.handle_write_event()
135 except ExitNow:
136 raise ExitNow
137 except:
138 obj.handle_error()
139 except KeyError:
140 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000141
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000142def poll3 (timeout=0.0, map=None):
143 # Use the poll() support added to the select module in Python 2.0
144 if map is None:
145 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000146 if timeout is not None:
147 # timeout is in milliseconds
148 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000149 pollster = select.poll()
150 if map:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000151 for fd, obj in map.items():
152 flags = 0
153 if obj.readable():
154 flags = select.POLLIN
155 if obj.writable():
156 flags = flags | select.POLLOUT
157 if flags:
158 pollster.register(fd, flags)
159 r = pollster.poll (timeout)
160 for fd, flags in r:
161 try:
162 obj = map[fd]
163 try:
164 if (flags & select.POLLIN):
165 obj.handle_read_event()
166 if (flags & select.POLLOUT):
167 obj.handle_write_event()
168 except ExitNow:
169 raise ExitNow
170 except:
171 obj.handle_error()
172 except KeyError:
173 pass
174
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000175def loop (timeout=30.0, use_poll=0, map=None):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000176
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000177 if map is None:
178 map=socket_map
179
Fred Drake526a1822000-09-11 04:00:46 +0000180 if use_poll:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000181 if hasattr (select, 'poll'):
182 poll_fun = poll3
183 else:
184 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000185 else:
186 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000187
Fred Drake526a1822000-09-11 04:00:46 +0000188 while map:
189 poll_fun (timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000190
191class dispatcher:
Fred Drake526a1822000-09-11 04:00:46 +0000192 debug = 0
193 connected = 0
194 accepting = 0
195 closing = 0
196 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000197
Fred Drake526a1822000-09-11 04:00:46 +0000198 def __init__ (self, sock=None, map=None):
199 if sock:
200 self.set_socket (sock, map)
201 # I think it should inherit this anyway
202 self.socket.setblocking (0)
203 self.connected = 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000204
Fred Drake526a1822000-09-11 04:00:46 +0000205 def __repr__ (self):
206 try:
207 status = []
208 if self.accepting and self.addr:
209 status.append ('listening')
210 elif self.connected:
211 status.append ('connected')
212 if self.addr:
Martin v. Löwis1efbe422001-09-11 15:11:27 +0000213 if type(self.addr) == types.TupleType:
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000214 status.append ('%s:%d' % self.addr)
215 else:
216 status.append (self.addr)
217 return '<%s %s at %x>' % (self.__class__.__name__,
218 ' '.join (status), id (self))
Fred Drake526a1822000-09-11 04:00:46 +0000219 except:
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000220 pass
Tim Peters8ae2df42001-05-02 05:54:44 +0000221
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000222 try:
223 ar = repr (self.addr)
224 except AttributeError:
225 ar = 'no self.addr!'
Tim Peters146965a2001-01-14 18:09:23 +0000226
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000227 return '<__repr__() failed for %s instance at %x (addr=%s)>' % \
228 (self.__class__.__name__, id (self), ar)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000229
Fred Drake526a1822000-09-11 04:00:46 +0000230 def add_channel (self, map=None):
231 #self.log_info ('adding channel %s' % self)
232 if map is None:
233 map=socket_map
234 map [self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000235
Fred Drake526a1822000-09-11 04:00:46 +0000236 def del_channel (self, map=None):
237 fd = self._fileno
238 if map is None:
239 map=socket_map
240 if map.has_key (fd):
241 #self.log_info ('closing channel %d:%s' % (fd, self))
242 del map [fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000243
Fred Drake526a1822000-09-11 04:00:46 +0000244 def create_socket (self, family, type):
245 self.family_and_type = family, type
246 self.socket = socket.socket (family, type)
247 self.socket.setblocking(0)
248 self._fileno = self.socket.fileno()
249 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000250
Fred Drake526a1822000-09-11 04:00:46 +0000251 def set_socket (self, sock, map=None):
252 self.__dict__['socket'] = sock
253 self._fileno = sock.fileno()
254 self.add_channel (map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000255
Fred Drake526a1822000-09-11 04:00:46 +0000256 def set_reuse_addr (self):
257 # try to re-use a server port if possible
258 try:
259 self.socket.setsockopt (
260 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000261 self.socket.getsockopt (socket.SOL_SOCKET,
262 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000263 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000264 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000265 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000266
Fred Drake526a1822000-09-11 04:00:46 +0000267 # ==================================================
268 # predicates for select()
269 # these are used as filters for the lists of sockets
270 # to pass to select().
271 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000272
Fred Drake526a1822000-09-11 04:00:46 +0000273 def readable (self):
274 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000275
Fred Drake526a1822000-09-11 04:00:46 +0000276 if os.name == 'mac':
277 # The macintosh will select a listening socket for
278 # write if you let it. What might this mean?
279 def writable (self):
280 return not self.accepting
281 else:
282 def writable (self):
283 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000284
Fred Drake526a1822000-09-11 04:00:46 +0000285 # ==================================================
286 # socket object methods.
287 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000288
Fred Drake526a1822000-09-11 04:00:46 +0000289 def listen (self, num):
290 self.accepting = 1
291 if os.name == 'nt' and num > 5:
292 num = 1
293 return self.socket.listen (num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000294
Fred Drake526a1822000-09-11 04:00:46 +0000295 def bind (self, addr):
296 self.addr = addr
297 return self.socket.bind (addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000298
Fred Drake526a1822000-09-11 04:00:46 +0000299 def connect (self, address):
300 self.connected = 0
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000301 # XXX why not use connect_ex?
Fred Drake526a1822000-09-11 04:00:46 +0000302 try:
303 self.socket.connect (address)
304 except socket.error, why:
305 if why[0] in (EINPROGRESS, EALREADY, EWOULDBLOCK):
306 return
307 else:
308 raise socket.error, why
309 self.connected = 1
310 self.handle_connect()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000311
Fred Drake526a1822000-09-11 04:00:46 +0000312 def accept (self):
313 try:
314 conn, addr = self.socket.accept()
315 return conn, addr
316 except socket.error, why:
317 if why[0] == EWOULDBLOCK:
318 pass
319 else:
320 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000321
Fred Drake526a1822000-09-11 04:00:46 +0000322 def send (self, data):
323 try:
324 result = self.socket.send (data)
325 return result
326 except socket.error, why:
327 if why[0] == EWOULDBLOCK:
328 return 0
329 else:
330 raise socket.error, why
331 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000332
Fred Drake526a1822000-09-11 04:00:46 +0000333 def recv (self, buffer_size):
334 try:
335 data = self.socket.recv (buffer_size)
336 if not data:
337 # a closed connection is indicated by signaling
338 # a read condition, and having recv() return 0.
339 self.handle_close()
340 return ''
341 else:
342 return data
343 except socket.error, why:
344 # winsock sometimes throws ENOTCONN
345 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
346 self.handle_close()
347 return ''
348 else:
349 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000350
Fred Drake526a1822000-09-11 04:00:46 +0000351 def close (self):
352 self.del_channel()
353 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000354
Fred Drake526a1822000-09-11 04:00:46 +0000355 # cheap inheritance, used to pass all other attribute
356 # references to the underlying socket object.
357 def __getattr__ (self, attr):
358 return getattr (self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000359
Fred Drake526a1822000-09-11 04:00:46 +0000360 # log and log_info maybe overriden to provide more sophisitcated
361 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000362 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000363
Fred Drake526a1822000-09-11 04:00:46 +0000364 def log (self, message):
365 sys.stderr.write ('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000366
Fred Drake526a1822000-09-11 04:00:46 +0000367 def log_info (self, message, type='info'):
368 if __debug__ or type != 'info':
369 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000370
Fred Drake526a1822000-09-11 04:00:46 +0000371 def handle_read_event (self):
372 if self.accepting:
373 # for an accepting socket, getting a read implies
374 # that we are connected
375 if not self.connected:
376 self.connected = 1
377 self.handle_accept()
378 elif not self.connected:
379 self.handle_connect()
380 self.connected = 1
381 self.handle_read()
382 else:
383 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000384
Fred Drake526a1822000-09-11 04:00:46 +0000385 def handle_write_event (self):
386 # getting a write implies that we are connected
387 if not self.connected:
388 self.handle_connect()
389 self.connected = 1
390 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000391
Fred Drake526a1822000-09-11 04:00:46 +0000392 def handle_expt_event (self):
393 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000394
Fred Drake526a1822000-09-11 04:00:46 +0000395 def handle_error (self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000396 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000397
Fred Drake526a1822000-09-11 04:00:46 +0000398 # sometimes a user repr method will crash.
399 try:
400 self_repr = repr (self)
401 except:
402 self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000403
Fred Drake526a1822000-09-11 04:00:46 +0000404 self.log_info (
405 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
406 self_repr,
407 t,
408 v,
409 tbinfo
410 ),
411 'error'
412 )
413 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000414
Fred Drake526a1822000-09-11 04:00:46 +0000415 def handle_expt (self):
416 self.log_info ('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000417
Fred Drake526a1822000-09-11 04:00:46 +0000418 def handle_read (self):
419 self.log_info ('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000420
Fred Drake526a1822000-09-11 04:00:46 +0000421 def handle_write (self):
422 self.log_info ('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000423
Fred Drake526a1822000-09-11 04:00:46 +0000424 def handle_connect (self):
425 self.log_info ('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000426
Fred Drake526a1822000-09-11 04:00:46 +0000427 def handle_accept (self):
428 self.log_info ('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000429
Fred Drake526a1822000-09-11 04:00:46 +0000430 def handle_close (self):
431 self.log_info ('unhandled close event', 'warning')
432 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000433
434# ---------------------------------------------------------------------------
435# adds simple buffered output capability, useful for simple clients.
436# [for more sophisticated usage use asynchat.async_chat]
437# ---------------------------------------------------------------------------
438
439class dispatcher_with_send (dispatcher):
Fred Drake526a1822000-09-11 04:00:46 +0000440 def __init__ (self, sock=None):
441 dispatcher.__init__ (self, sock)
442 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000443
Fred Drake526a1822000-09-11 04:00:46 +0000444 def initiate_send (self):
445 num_sent = 0
446 num_sent = dispatcher.send (self, self.out_buffer[:512])
447 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000448
Fred Drake526a1822000-09-11 04:00:46 +0000449 def handle_write (self):
450 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000451
Fred Drake526a1822000-09-11 04:00:46 +0000452 def writable (self):
453 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000454
Fred Drake526a1822000-09-11 04:00:46 +0000455 def send (self, data):
456 if self.debug:
457 self.log_info ('sending %s' % repr(data))
458 self.out_buffer = self.out_buffer + data
459 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000460
461# ---------------------------------------------------------------------------
462# used for debugging.
463# ---------------------------------------------------------------------------
464
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000465def compact_traceback ():
Fred Drake526a1822000-09-11 04:00:46 +0000466 t,v,tb = sys.exc_info()
467 tbinfo = []
468 while 1:
469 tbinfo.append ((
470 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000471 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000472 str(tb.tb_lineno)
473 ))
474 tb = tb.tb_next
475 if not tb:
476 break
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000477
Fred Drake526a1822000-09-11 04:00:46 +0000478 # just to be safe
479 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000480
Fred Drake526a1822000-09-11 04:00:46 +0000481 file, function, line = tbinfo[-1]
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000482 info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
Fred Drake526a1822000-09-11 04:00:46 +0000483 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000484
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000485def close_all (map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000486 if map is None:
487 map=socket_map
488 for x in map.values():
489 x.socket.close()
490 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000491
492# Asynchronous File I/O:
493#
494# After a little research (reading man pages on various unixen, and
495# digging through the linux kernel), I've determined that select()
496# isn't meant for doing doing asynchronous file i/o.
497# Heartening, though - reading linux/mm/filemap.c shows that linux
498# supports asynchronous read-ahead. So _MOST_ of the time, the data
499# will be sitting in memory for us already when we go to read it.
500#
501# What other OS's (besides NT) support async file i/o? [VMS?]
502#
503# Regardless, this is useful for pipes, and stdin/stdout...
504
505import os
506if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000507 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000508
Fred Drake526a1822000-09-11 04:00:46 +0000509 class file_wrapper:
510 # here we override just enough to make a file
511 # look like a socket for the purposes of asyncore.
512 def __init__ (self, fd):
513 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000514
Fred Drake526a1822000-09-11 04:00:46 +0000515 def recv (self, *args):
516 return apply (os.read, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000517
Fred Drake526a1822000-09-11 04:00:46 +0000518 def send (self, *args):
519 return apply (os.write, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000520
Fred Drake526a1822000-09-11 04:00:46 +0000521 read = recv
522 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000523
Fred Drake526a1822000-09-11 04:00:46 +0000524 def close (self):
525 return os.close (self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000526
Fred Drake526a1822000-09-11 04:00:46 +0000527 def fileno (self):
528 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000529
Fred Drake526a1822000-09-11 04:00:46 +0000530 class file_dispatcher (dispatcher):
531 def __init__ (self, fd):
532 dispatcher.__init__ (self)
533 self.connected = 1
534 # set it to non-blocking mode
Fred Drakea94414a2001-05-10 15:33:31 +0000535 flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0)
536 flags = flags | os.O_NONBLOCK
537 fcntl.fcntl (fd, fcntl.F_SETFL, flags)
Fred Drake526a1822000-09-11 04:00:46 +0000538 self.set_file (fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000539
Fred Drake526a1822000-09-11 04:00:46 +0000540 def set_file (self, fd):
541 self._fileno = fd
542 self.socket = file_wrapper (fd)
543 self.add_channel()