blob: 4864eb430189a1cb34de9fd3b386bd5eb9c6556b [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
53
54import os
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +000055from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \
Tim Peters7c005af2001-08-20 21:48:00 +000056 ENOTCONN, ESHUTDOWN
Guido van Rossum0039d7b1999-01-12 20:19:27 +000057
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000058try:
Fred Drake526a1822000-09-11 04:00:46 +000059 socket_map
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000060except NameError:
Fred Drake526a1822000-09-11 04:00:46 +000061 socket_map = {}
Guido van Rossum0039d7b1999-01-12 20:19:27 +000062
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000063class ExitNow (exceptions.Exception):
Fred Drake526a1822000-09-11 04:00:46 +000064 pass
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +000065
66DEBUG = 0
67
68def poll (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +000069 global DEBUG
70 if map is None:
71 map = socket_map
72 if map:
73 r = []; w = []; e = []
74 for fd, obj in map.items():
75 if obj.readable():
76 r.append (fd)
77 if obj.writable():
78 w.append (fd)
79 r,w,e = select.select (r,w,e, timeout)
Guido van Rossum0039d7b1999-01-12 20:19:27 +000080
Fred Drake526a1822000-09-11 04:00:46 +000081 if DEBUG:
82 print r,w,e
Guido van Rossum0039d7b1999-01-12 20:19:27 +000083
Fred Drake526a1822000-09-11 04:00:46 +000084 for fd in r:
85 try:
86 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +000087 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +000088 continue
89
90 try:
91 obj.handle_read_event()
92 except ExitNow:
93 raise ExitNow
94 except:
95 obj.handle_error()
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]
Fred Drake526a1822000-09-11 04:00:46 +0000100 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000101 continue
102
103 try:
104 obj.handle_write_event()
105 except ExitNow:
106 raise ExitNow
107 except:
108 obj.handle_error()
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000109
110def poll2 (timeout=0.0, map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000111 import poll
112 if map is None:
113 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000114 if timeout is not None:
115 # timeout is in milliseconds
116 timeout = int(timeout*1000)
Fred Drake526a1822000-09-11 04:00:46 +0000117 if map:
118 l = []
119 for fd, obj in map.items():
120 flags = 0
121 if obj.readable():
122 flags = poll.POLLIN
123 if obj.writable():
124 flags = flags | poll.POLLOUT
125 if flags:
126 l.append ((fd, flags))
127 r = poll.poll (l, timeout)
128 for fd, flags in r:
129 try:
130 obj = map[fd]
Fred Drake526a1822000-09-11 04:00:46 +0000131 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000132 continue
133
134 try:
135 if (flags & poll.POLLIN):
136 obj.handle_read_event()
137 if (flags & poll.POLLOUT):
138 obj.handle_write_event()
139 except ExitNow:
140 raise ExitNow
141 except:
142 obj.handle_error()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000143
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000144def poll3 (timeout=0.0, map=None):
145 # Use the poll() support added to the select module in Python 2.0
146 if map is None:
147 map=socket_map
Martin v. Löwisf6cc07c2001-09-19 17:31:47 +0000148 if timeout is not None:
149 # timeout is in milliseconds
150 timeout = int(timeout*1000)
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000151 pollster = select.poll()
152 if map:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000153 for fd, obj in map.items():
154 flags = 0
155 if obj.readable():
156 flags = select.POLLIN
157 if obj.writable():
158 flags = flags | select.POLLOUT
159 if flags:
160 pollster.register(fd, flags)
161 r = pollster.poll (timeout)
162 for fd, flags in r:
163 try:
164 obj = map[fd]
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000165 except KeyError:
Martin v. Löwis6ec9a362001-10-09 10:10:33 +0000166 continue
167
168 try:
169 if (flags & select.POLLIN):
170 obj.handle_read_event()
171 if (flags & select.POLLOUT):
172 obj.handle_write_event()
173 except ExitNow:
174 raise ExitNow
175 except:
176 obj.handle_error()
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000177
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000178def loop (timeout=30.0, use_poll=0, map=None):
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000179
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000180 if map is None:
181 map=socket_map
182
Fred Drake526a1822000-09-11 04:00:46 +0000183 if use_poll:
Andrew M. Kuchlingaf6963c2001-01-24 15:50:19 +0000184 if hasattr (select, 'poll'):
185 poll_fun = poll3
186 else:
187 poll_fun = poll2
Fred Drake526a1822000-09-11 04:00:46 +0000188 else:
189 poll_fun = poll
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000190
Fred Drake526a1822000-09-11 04:00:46 +0000191 while map:
192 poll_fun (timeout, map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000193
194class dispatcher:
Fred Drake526a1822000-09-11 04:00:46 +0000195 debug = 0
196 connected = 0
197 accepting = 0
198 closing = 0
199 addr = None
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000200
Fred Drake526a1822000-09-11 04:00:46 +0000201 def __init__ (self, sock=None, map=None):
202 if sock:
203 self.set_socket (sock, map)
204 # I think it should inherit this anyway
205 self.socket.setblocking (0)
206 self.connected = 1
Andrew M. Kuchling4602c1b2001-10-03 17:07:25 +0000207 self.addr = sock.getpeername()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000208
Fred Drake526a1822000-09-11 04:00:46 +0000209 def __repr__ (self):
Martin v. Löwis29103c72001-10-18 17:33:19 +0000210 status = [self.__class__.__module__+"."+self.__class__.__name__]
211 if self.accepting and self.addr:
212 status.append ('listening')
213 elif self.connected:
214 status.append ('connected')
215 if self.addr is not None:
216 try:
217 status.append ('%s:%d' % self.addr)
218 except TypeError:
219 status.append (repr(self.addr))
220 return '<%s at %#x>' % (' '.join (status), id (self))
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000221
Fred Drake526a1822000-09-11 04:00:46 +0000222 def add_channel (self, map=None):
223 #self.log_info ('adding channel %s' % self)
224 if map is None:
225 map=socket_map
226 map [self._fileno] = self
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000227
Fred Drake526a1822000-09-11 04:00:46 +0000228 def del_channel (self, map=None):
229 fd = self._fileno
230 if map is None:
231 map=socket_map
232 if map.has_key (fd):
233 #self.log_info ('closing channel %d:%s' % (fd, self))
234 del map [fd]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000235
Fred Drake526a1822000-09-11 04:00:46 +0000236 def create_socket (self, family, type):
237 self.family_and_type = family, type
238 self.socket = socket.socket (family, type)
239 self.socket.setblocking(0)
240 self._fileno = self.socket.fileno()
241 self.add_channel()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000242
Fred Drake526a1822000-09-11 04:00:46 +0000243 def set_socket (self, sock, map=None):
244 self.__dict__['socket'] = sock
245 self._fileno = sock.fileno()
246 self.add_channel (map)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000247
Fred Drake526a1822000-09-11 04:00:46 +0000248 def set_reuse_addr (self):
249 # try to re-use a server port if possible
250 try:
251 self.socket.setsockopt (
252 socket.SOL_SOCKET, socket.SO_REUSEADDR,
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000253 self.socket.getsockopt (socket.SOL_SOCKET,
254 socket.SO_REUSEADDR) | 1
Fred Drake526a1822000-09-11 04:00:46 +0000255 )
Fred Drake9f9b5932001-05-11 18:28:54 +0000256 except socket.error:
Fred Drake526a1822000-09-11 04:00:46 +0000257 pass
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000258
Fred Drake526a1822000-09-11 04:00:46 +0000259 # ==================================================
260 # predicates for select()
261 # these are used as filters for the lists of sockets
262 # to pass to select().
263 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000264
Fred Drake526a1822000-09-11 04:00:46 +0000265 def readable (self):
266 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000267
Fred Drake526a1822000-09-11 04:00:46 +0000268 if os.name == 'mac':
269 # The macintosh will select a listening socket for
270 # write if you let it. What might this mean?
271 def writable (self):
272 return not self.accepting
273 else:
274 def writable (self):
275 return 1
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000276
Fred Drake526a1822000-09-11 04:00:46 +0000277 # ==================================================
278 # socket object methods.
279 # ==================================================
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000280
Fred Drake526a1822000-09-11 04:00:46 +0000281 def listen (self, num):
282 self.accepting = 1
283 if os.name == 'nt' and num > 5:
284 num = 1
285 return self.socket.listen (num)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000286
Fred Drake526a1822000-09-11 04:00:46 +0000287 def bind (self, addr):
288 self.addr = addr
289 return self.socket.bind (addr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000290
Fred Drake526a1822000-09-11 04:00:46 +0000291 def connect (self, address):
292 self.connected = 0
Jeremy Hylton12e73bb2001-04-20 19:04:55 +0000293 # XXX why not use connect_ex?
Fred Drake526a1822000-09-11 04:00:46 +0000294 try:
295 self.socket.connect (address)
296 except socket.error, why:
297 if why[0] in (EINPROGRESS, EALREADY, EWOULDBLOCK):
298 return
299 else:
300 raise socket.error, why
Andrew M. Kuchling4602c1b2001-10-03 17:07:25 +0000301 self.addr = address
Fred Drake526a1822000-09-11 04:00:46 +0000302 self.connected = 1
303 self.handle_connect()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000304
Fred Drake526a1822000-09-11 04:00:46 +0000305 def accept (self):
306 try:
307 conn, addr = self.socket.accept()
308 return conn, addr
309 except socket.error, why:
310 if why[0] == EWOULDBLOCK:
311 pass
312 else:
313 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000314
Fred Drake526a1822000-09-11 04:00:46 +0000315 def send (self, data):
316 try:
317 result = self.socket.send (data)
318 return result
319 except socket.error, why:
320 if why[0] == EWOULDBLOCK:
321 return 0
322 else:
323 raise socket.error, why
324 return 0
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000325
Fred Drake526a1822000-09-11 04:00:46 +0000326 def recv (self, buffer_size):
327 try:
328 data = self.socket.recv (buffer_size)
329 if not data:
330 # a closed connection is indicated by signaling
331 # a read condition, and having recv() return 0.
332 self.handle_close()
333 return ''
334 else:
335 return data
336 except socket.error, why:
337 # winsock sometimes throws ENOTCONN
338 if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]:
339 self.handle_close()
340 return ''
341 else:
342 raise socket.error, why
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000343
Fred Drake526a1822000-09-11 04:00:46 +0000344 def close (self):
345 self.del_channel()
346 self.socket.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000347
Fred Drake526a1822000-09-11 04:00:46 +0000348 # cheap inheritance, used to pass all other attribute
349 # references to the underlying socket object.
350 def __getattr__ (self, attr):
351 return getattr (self.socket, attr)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000352
Fred Drake526a1822000-09-11 04:00:46 +0000353 # log and log_info maybe overriden to provide more sophisitcated
354 # logging and warning methods. In general, log is for 'hit' logging
Tim Peters146965a2001-01-14 18:09:23 +0000355 # and 'log_info' is for informational, warning and error logging.
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000356
Fred Drake526a1822000-09-11 04:00:46 +0000357 def log (self, message):
358 sys.stderr.write ('log: %s\n' % str(message))
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000359
Fred Drake526a1822000-09-11 04:00:46 +0000360 def log_info (self, message, type='info'):
361 if __debug__ or type != 'info':
362 print '%s: %s' % (type, message)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000363
Fred Drake526a1822000-09-11 04:00:46 +0000364 def handle_read_event (self):
365 if self.accepting:
366 # for an accepting socket, getting a read implies
367 # that we are connected
368 if not self.connected:
369 self.connected = 1
370 self.handle_accept()
371 elif not self.connected:
372 self.handle_connect()
373 self.connected = 1
374 self.handle_read()
375 else:
376 self.handle_read()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000377
Fred Drake526a1822000-09-11 04:00:46 +0000378 def handle_write_event (self):
379 # getting a write implies that we are connected
380 if not self.connected:
381 self.handle_connect()
382 self.connected = 1
383 self.handle_write()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000384
Fred Drake526a1822000-09-11 04:00:46 +0000385 def handle_expt_event (self):
386 self.handle_expt()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000387
Fred Drake526a1822000-09-11 04:00:46 +0000388 def handle_error (self):
Jeremy Hyltona8b5f7d2001-08-10 14:30:35 +0000389 nil, t, v, tbinfo = compact_traceback()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000390
Fred Drake526a1822000-09-11 04:00:46 +0000391 # sometimes a user repr method will crash.
392 try:
393 self_repr = repr (self)
394 except:
395 self_repr = '<__repr__ (self) failed for object at %0x>' % id(self)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000396
Fred Drake526a1822000-09-11 04:00:46 +0000397 self.log_info (
398 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
399 self_repr,
400 t,
401 v,
402 tbinfo
403 ),
404 'error'
405 )
406 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000407
Fred Drake526a1822000-09-11 04:00:46 +0000408 def handle_expt (self):
409 self.log_info ('unhandled exception', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000410
Fred Drake526a1822000-09-11 04:00:46 +0000411 def handle_read (self):
412 self.log_info ('unhandled read event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000413
Fred Drake526a1822000-09-11 04:00:46 +0000414 def handle_write (self):
415 self.log_info ('unhandled write event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000416
Fred Drake526a1822000-09-11 04:00:46 +0000417 def handle_connect (self):
418 self.log_info ('unhandled connect event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000419
Fred Drake526a1822000-09-11 04:00:46 +0000420 def handle_accept (self):
421 self.log_info ('unhandled accept event', 'warning')
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000422
Fred Drake526a1822000-09-11 04:00:46 +0000423 def handle_close (self):
424 self.log_info ('unhandled close event', 'warning')
425 self.close()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000426
427# ---------------------------------------------------------------------------
428# adds simple buffered output capability, useful for simple clients.
429# [for more sophisticated usage use asynchat.async_chat]
430# ---------------------------------------------------------------------------
431
432class dispatcher_with_send (dispatcher):
Fred Drake526a1822000-09-11 04:00:46 +0000433 def __init__ (self, sock=None):
434 dispatcher.__init__ (self, sock)
435 self.out_buffer = ''
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000436
Fred Drake526a1822000-09-11 04:00:46 +0000437 def initiate_send (self):
438 num_sent = 0
439 num_sent = dispatcher.send (self, self.out_buffer[:512])
440 self.out_buffer = self.out_buffer[num_sent:]
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000441
Fred Drake526a1822000-09-11 04:00:46 +0000442 def handle_write (self):
443 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000444
Fred Drake526a1822000-09-11 04:00:46 +0000445 def writable (self):
446 return (not self.connected) or len(self.out_buffer)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000447
Fred Drake526a1822000-09-11 04:00:46 +0000448 def send (self, data):
449 if self.debug:
450 self.log_info ('sending %s' % repr(data))
451 self.out_buffer = self.out_buffer + data
452 self.initiate_send()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000453
454# ---------------------------------------------------------------------------
455# used for debugging.
456# ---------------------------------------------------------------------------
457
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000458def compact_traceback ():
Fred Drake526a1822000-09-11 04:00:46 +0000459 t,v,tb = sys.exc_info()
460 tbinfo = []
461 while 1:
462 tbinfo.append ((
463 tb.tb_frame.f_code.co_filename,
Tim Peters146965a2001-01-14 18:09:23 +0000464 tb.tb_frame.f_code.co_name,
Fred Drake526a1822000-09-11 04:00:46 +0000465 str(tb.tb_lineno)
466 ))
467 tb = tb.tb_next
468 if not tb:
469 break
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000470
Fred Drake526a1822000-09-11 04:00:46 +0000471 # just to be safe
472 del tb
Guido van Rossuma8d0f4f1999-06-08 13:20:05 +0000473
Fred Drake526a1822000-09-11 04:00:46 +0000474 file, function, line = tbinfo[-1]
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000475 info = '[' + '] ['.join(map(lambda x: '|'.join(x), tbinfo)) + ']'
Fred Drake526a1822000-09-11 04:00:46 +0000476 return (file, function, line), t, v, info
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000477
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000478def close_all (map=None):
Fred Drake526a1822000-09-11 04:00:46 +0000479 if map is None:
480 map=socket_map
481 for x in map.values():
482 x.socket.close()
483 map.clear()
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000484
485# Asynchronous File I/O:
486#
487# After a little research (reading man pages on various unixen, and
488# digging through the linux kernel), I've determined that select()
489# isn't meant for doing doing asynchronous file i/o.
490# Heartening, though - reading linux/mm/filemap.c shows that linux
491# supports asynchronous read-ahead. So _MOST_ of the time, the data
492# will be sitting in memory for us already when we go to read it.
493#
494# What other OS's (besides NT) support async file i/o? [VMS?]
495#
496# Regardless, this is useful for pipes, and stdin/stdout...
497
498import os
499if os.name == 'posix':
Fred Drake526a1822000-09-11 04:00:46 +0000500 import fcntl
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000501
Fred Drake526a1822000-09-11 04:00:46 +0000502 class file_wrapper:
503 # here we override just enough to make a file
504 # look like a socket for the purposes of asyncore.
505 def __init__ (self, fd):
506 self.fd = fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000507
Fred Drake526a1822000-09-11 04:00:46 +0000508 def recv (self, *args):
509 return apply (os.read, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000510
Fred Drake526a1822000-09-11 04:00:46 +0000511 def send (self, *args):
512 return apply (os.write, (self.fd,)+args)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000513
Fred Drake526a1822000-09-11 04:00:46 +0000514 read = recv
515 write = send
Andrew M. Kuchlingda85a272000-09-08 20:30:39 +0000516
Fred Drake526a1822000-09-11 04:00:46 +0000517 def close (self):
518 return os.close (self.fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000519
Fred Drake526a1822000-09-11 04:00:46 +0000520 def fileno (self):
521 return self.fd
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000522
Fred Drake526a1822000-09-11 04:00:46 +0000523 class file_dispatcher (dispatcher):
524 def __init__ (self, fd):
525 dispatcher.__init__ (self)
526 self.connected = 1
527 # set it to non-blocking mode
Fred Drakea94414a2001-05-10 15:33:31 +0000528 flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0)
529 flags = flags | os.O_NONBLOCK
530 fcntl.fcntl (fd, fcntl.F_SETFL, flags)
Fred Drake526a1822000-09-11 04:00:46 +0000531 self.set_file (fd)
Guido van Rossum0039d7b1999-01-12 20:19:27 +0000532
Fred Drake526a1822000-09-11 04:00:46 +0000533 def set_file (self, fd):
534 self._fileno = fd
535 self.socket = file_wrapper (fd)
536 self.add_channel()