~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to doc/howto/listings/pclients/multiple.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-01-17 14:52:35 UTC
  • mfrom: (1.1.5 upstream) (2.1.2 etch)
  • Revision ID: james.westby@ubuntu.com-20070117145235-btmig6qfmqfen0om
Tags: 2.5.0-0ubuntu1
New upstream version, compatible with python2.5.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from twisted.spread import pb
2
 
 
3
 
class MultipleClientPerspective(pb.Perspective):
4
 
    """Many clients may use this Perspective at once."""
5
 
 
6
 
    # This example is from twisted.manhole.service.Perspective.
7
 
 
8
 
    def __init__(self, perspectiveName, identityName="Nobody"):
9
 
        pb.Perspective.__init__(self, perspectiveName, identityName)
10
 
        self.clients = {}
11
 
 
12
 
    def attached(self, client, identity):
13
 
        # The clients dictionary is really only used as a set and not as a
14
 
        # mapping, but we go ahead and throw the Identity into the value slot
15
 
        # because hey, it's there.
16
 
        self.clients[client] = identity
17
 
        return self
18
 
 
19
 
    def detached(self, client, identity):
20
 
        try:
21
 
            del self.clients[client]
22
 
        except KeyError:
23
 
            # This is probably something as benign as the client being removed
24
 
            # by a DeadReferenceError in sendMessage and again when the broker
25
 
            # formally closes down.  No big deal.
26
 
            pass
27
 
 
28
 
    def sendMessage(self, message):
29
 
        """Pass a message to my clients' console.
30
 
        """
31
 
        for client in self.clients.keys():
32
 
            try:
33
 
                client.callRemote('message', message)
34
 
            except pb.DeadReferenceError:
35
 
                # Stale broker.  This is the error you get if in the process
36
 
                # of doing the callRemote, the broker finds out the transport
37
 
                # just died, or something along those lines.  So remove that
38
 
                # client from our list.
39
 
                self.detached(client, None)
40
 
 
41
 
    def __getstate__(self):
42
 
        state = styles.Versioned.__getstate__(self)
43
 
        state['clients'] = {}
44
 
        return state