Python Manual Benutzerhandbuch

Seite von 124
Event Framework
32
Other possible values for the third argument are
SOCKET_POLLOUT
and
SOCKET_POLLPRI
. The
value
SOCKET_POLLPRI
is similar to
SOCKET_POLLIN
except that it relates to there being priority
out of band data being available for reading. Out of band data is not a feature which is used much these
days and isn’t implemented the same on all systems. It is probably best to avoid using out of band data.
A final value of
SOCKET_POLLOUT
indicates interest in when data can be safely written to the socket
without the call blocking. Note that this will generally nearly always be the case, so you should only
subscribe to this event on a socket, when you know that writing to the socket would cause it to block.
Once you have been notified that it is safe to write to a socket and you have written your data, you
should immediately unsubscribe to this event on a socket, otherwise your callback will continually be
called.
class Agent(netsvc.Agent):
def __init__(self,host,port):
netsvc.Agent.__init__(self)
self._host = host
self._port = port
self.scheduleAction(self.connect,netsvc.STANDARD_JOB)
def connect(self):
self._sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
self._sock.connect((host,port))
except:
dispatcher.stop()
else:
self.subscribeSocket(self.read,self._sock.fileno())
def read(self,fileno,event):
if fileno != self._sock.fileno():
return
if event == netsvc.SOCKET_POLLIN:
data = self._sock.recv(1024)
if len(data) == 0:
self.unsubscribeSocket(self._sock.fileno())
self._sock.close()
dispatcher.stop()
else:
sys.stdout.write(data)
When you are no longer interested in a particular event on a socket, you can unsubscribe to that event
using the "
unsubscribeSocket()
" member function. If called with only a single argument, all
events currently of interest on that socket will be unsubscribed. To unsubscribe to only a specific event
type, pass the type of event as the second argument.
Program Signals
The most common circumstance in which an application may receive a program signal is when it is
being killed as result of a user interrupting it by typing control-C, or if running UNIX, when the oper-