1 # -*- Mode: Python; tab-width: 4 -*-
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 # ======================================================================
42 from errno
import EALREADY
, EINPROGRESS
, EWOULDBLOCK
, ECONNRESET
, ENOTCONN
, ESHUTDOWN
46 def poll (timeout
=0.0):
48 r
= []; w
= []; e
= []
49 for s
in socket_map
.keys():
55 (r
,w
,e
) = select
.select (r
,w
,e
, timeout
)
64 x
.handle_write_event()
68 def poll2 (timeout
=0.0):
70 # timeout is in milliseconds
71 timeout
= int(timeout
*1000)
74 for s
in socket_map
.keys():
75 fd_map
[s
.fileno()] = s
77 for fd
, s
in fd_map
.items():
82 flags
= flags | poll
.POLLOUT
85 r
= poll
.poll (l
, timeout
)
89 if (flags
& poll
.POLLIN
):
91 if (flags
& poll
.POLLOUT
):
92 s
.handle_write_event()
93 if (flags
& poll
.POLLERR
):
99 def loop (timeout
=30.0, use_poll
=0):
116 def __init__ (self
, sock
=None):
118 self
.set_socket (sock
)
119 # I think it should inherit this anyway
120 self
.socket
.setblocking (0)
126 if self
.accepting
and self
.addr
:
127 status
.append ('listening')
129 status
.append ('connected')
131 status
.append ('%s:%d' % self
.addr
)
132 return '<%s %s at %x>' % (
133 self
.__class
__.__name
__,
134 string
.join (status
, ' '),
143 return '<__repr__ (self) failed for object at %x (addr=%s)>' % (id(self
),ar
)
145 def add_channel (self
):
147 self
.log ('adding channel %s' % self
)
148 socket_map
[self
] = 1
150 def del_channel (self
):
151 if socket_map
.has_key (self
):
153 self
.log ('closing channel %d:%s' % (self
.fileno(), self
))
154 del socket_map
[self
]
156 def create_socket (self
, family
, type):
157 self
.family_and_type
= family
, type
158 self
.socket
= socket
.socket (family
, type)
159 self
.socket
.setblocking(0)
162 def set_socket (self
, socket
):
163 # This is done so we can be called safely from __init__
164 self
.__dict
__['socket'] = socket
167 def set_reuse_addr (self
):
168 # try to re-use a server port if possible
170 self
.socket
.setsockopt (
171 socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
,
172 self
.socket
.getsockopt (socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
) |
1
177 # ==================================================
178 # predicates for select()
179 # these are used as filters for the lists of sockets
180 # to pass to select().
181 # ==================================================
187 # The macintosh will select a listening socket for
188 # write if you let it. What might this mean?
190 return not self
.accepting
195 # ==================================================
196 # socket object methods.
197 # ==================================================
199 def listen (self
, num
):
201 if os
.name
== 'nt' and num
> 5:
203 return self
.socket
.listen (num
)
205 def bind (self
, addr
):
207 return self
.socket
.bind (addr
)
209 def connect (self
, address
):
212 self
.socket
.connect (address
)
213 except socket
.error
, why
:
214 if why
[0] in (EINPROGRESS
, EALREADY
, EWOULDBLOCK
):
217 raise socket
.error
, why
219 self
.handle_connect()
223 conn
, addr
= self
.socket
.accept()
225 except socket
.error
, why
:
226 if why
[0] == EWOULDBLOCK
:
229 raise socket
.error
, why
231 def send (self
, data
):
233 result
= self
.socket
.send (data
)
235 except socket
.error
, why
:
236 if why
[0] == EWOULDBLOCK
:
239 raise socket
.error
, why
242 def recv (self
, buffer_size
):
244 data
= self
.socket
.recv (buffer_size
)
246 # a closed connection is indicated by signaling
247 # a read condition, and having recv() return 0.
252 except socket
.error
, why
:
253 # winsock sometimes throws ENOTCONN
254 if why
[0] in [ECONNRESET
, ENOTCONN
, ESHUTDOWN
]:
258 raise socket
.error
, why
264 # cheap inheritance, used to pass all other attribute
265 # references to the underlying socket object.
266 # NOTE: this may be removed soon for performance reasons.
267 def __getattr__ (self
, attr
):
268 return getattr (self
.socket
, attr
)
270 def log (self
, message
):
271 print 'log:', message
273 def handle_read_event (self
):
275 # for an accepting socket, getting a read implies
276 # that we are connected
277 if not self
.connected
:
280 elif not self
.connected
:
281 self
.handle_connect()
287 def handle_write_event (self
):
288 # getting a write implies that we are connected
289 if not self
.connected
:
290 self
.handle_connect()
294 def handle_expt_event (self
):
297 def handle_error (self
):
298 (file,fun
,line
), t
, v
, tbinfo
= compact_traceback()
300 # sometimes a user repr method will crash.
302 self_repr
= repr (self
)
304 self_repr
= '<__repr__ (self) failed for object at %0x>' % id(self
)
307 'uncaptured python exception, closing channel %s (%s:%s %s)' % (
316 def handle_expt (self
):
318 self
.log ('unhandled exception')
320 def handle_read (self
):
322 self
.log ('unhandled read event')
324 def handle_write (self
):
326 self
.log ('unhandled write event')
328 def handle_connect (self
):
330 self
.log ('unhandled connect event')
332 def handle_accept (self
):
334 self
.log ('unhandled accept event')
336 def handle_close (self
):
338 self
.log ('unhandled close event')
341 # ---------------------------------------------------------------------------
342 # adds simple buffered output capability, useful for simple clients.
343 # [for more sophisticated usage use asynchat.async_chat]
344 # ---------------------------------------------------------------------------
346 class dispatcher_with_send (dispatcher
):
347 def __init__ (self
, sock
=None):
348 dispatcher
.__init
__ (self
, sock
)
351 def initiate_send (self
):
353 num_sent
= dispatcher
.send (self
, self
.out_buffer
[:512])
354 self
.out_buffer
= self
.out_buffer
[num_sent
:]
356 def handle_write (self
):
360 return (not self
.connected
) or len(self
.out_buffer
)
362 def send (self
, data
):
364 self
.log ('sending %s' % repr(data
))
365 self
.out_buffer
= self
.out_buffer
+ data
368 # ---------------------------------------------------------------------------
369 # used for debugging.
370 # ---------------------------------------------------------------------------
372 def compact_traceback ():
373 t
,v
,tb
= sys
.exc_info()
377 tb
.tb_frame
.f_code
.co_filename
,
378 tb
.tb_frame
.f_code
.co_name
,
388 file, function
, line
= tbinfo
[-1]
389 info
= '[' + string
.join (
391 lambda x
: string
.join (x
, '|'),
396 return (file, function
, line
), t
, v
, info
400 for x
in socket_map
.keys():
404 # Asynchronous File I/O:
406 # After a little research (reading man pages on various unixen, and
407 # digging through the linux kernel), I've determined that select()
408 # isn't meant for doing doing asynchronous file i/o.
409 # Heartening, though - reading linux/mm/filemap.c shows that linux
410 # supports asynchronous read-ahead. So _MOST_ of the time, the data
411 # will be sitting in memory for us already when we go to read it.
413 # What other OS's (besides NT) support async file i/o? [VMS?]
415 # Regardless, this is useful for pipes, and stdin/stdout...
418 if os
.name
== 'posix':
423 # here we override just enough to make a file
424 # look like a socket for the purposes of asyncore.
425 def __init__ (self
, fd
):
428 def recv (self
, *args
):
429 return apply (os
.read
, (self
.fd
,)+args
)
431 def write (self
, *args
):
432 return apply (os
.write
, (self
.fd
,)+args
)
435 return os
.close (self
.fd
)
440 class file_dispatcher (dispatcher
):
441 def __init__ (self
, fd
):
442 dispatcher
.__init
__ (self
)
444 # set it to non-blocking mode
445 flags
= fcntl
.fcntl (fd
, FCNTL
.F_GETFL
, 0)
446 flags
= flags | FCNTL
.O_NONBLOCK
447 fcntl
.fcntl (fd
, FCNTL
.F_SETFL
, flags
)
450 def set_file (self
, fd
):
451 self
.socket
= file_wrapper (fd
)