File: client_using_clientservice.py

package info (click to toggle)
python-autobahn 23.1.2%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,424 kB
  • sloc: python: 38,620; javascript: 2,705; makefile: 899; ansic: 373; sh: 63
file content (79 lines) | stat: -rw-r--r-- 2,378 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import txaio
txaio.use_twisted()

from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.application.internet import ClientService

from autobahn.wamp.types import ComponentConfig
from autobahn.twisted.wamp import ApplicationSession, WampWebSocketClientFactory

def add2(a, b):
    print('add2 called: {} {}'.format(a, b))
    return a + b


class MyAppSession(ApplicationSession):

    def __init__(self, config):
        ApplicationSession.__init__(self, config)
        self._countdown = 5

    def onConnect(self):
        self.log.info('transport connected')

        # lets join a realm .. normally, we would also specify
        # how we would like to authenticate here
        self.join(self.config.realm)

    def onChallenge(self, challenge):
        self.log.info('authentication challenge received')

    @inlineCallbacks
    def onJoin(self, details):
        self.log.info('session joined: {}'.format(details))

        yield self.register(add2, 'com.example.add2')

        for i in range(10):
            res = yield self.call('com.example.add2', 23, i)
            self.log.info('result: {}'.format(res))

        yield self.leave()

    def onLeave(self, details):
        self.log.info('session left: {}'.format(details))
        self.disconnect()

    def onDisconnect(self):
        self.log.info('transport disconnected')
        # this is to clean up stuff. it is not our business to
        # possibly reconnect the underlying connection
        self._countdown -= 1
        if self._countdown <= 0:
            try:
                reactor.stop()
            except ReactorNotRunning:
                pass


if __name__ == '__main__':
    txaio.start_logging(level='info')

    # create a WAMP session object. this is reused across multiple
    # reconnects (if automatically reconnected)
    session = MyAppSession(ComponentConfig('realm1', {}))

    # create a WAMP transport factory
    transport = WampWebSocketClientFactory(session, url='ws://localhost:8080/ws')

    # create a connecting endpoint
    endpoint = TCP4ClientEndpoint(reactor, 'localhost', 8080)

    # create and start an automatically reconnecting client
    service = ClientService(endpoint, transport)
    service.startService()

    # enter the event loop
    reactor.run()