autobahn - read the docs · wamp is a routed protocol, so you need a wamp router. we suggest...

148
autobahn Release 19.10.1 Sep 30, 2019

Upload: others

Post on 31-Aug-2019

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahnRelease 19.10.1

Sep 30, 2019

Page 2: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother
Page 3: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

Contents

1 Autobahn|Python 11.1 Autobahn Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 What can I do with Autobahn? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Show me some code! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.4 Where to start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5 Get in touch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.6 Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.7 Release Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.8 Sitemap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Installation 72.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.1.1 Supported Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.1.2 Performance Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.2 Installing Autobahn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.1 Using Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.2 Install from PyPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.3 Install from Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.4 Install Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2.5 Windows Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.3 Check the Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4 Depending on Autobahn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

3 Asynchronous Programming 113.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3.1.1 The asynchronous programming approach . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.1.2 Other forms of Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.1.3 Twisted or asyncio? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

3.2 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.2.1 Twisted Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.2.2 Asyncio Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

3.3 Asynchronous Programming Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.3.1 Twisted Deferreds and inlineCallbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.3.2 Asyncio Futures and Coroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

4 WebSocket Programming 194.1 Creating Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

i

Page 4: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

4.1.1 Server Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194.1.2 Receiving Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.1.3 Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.1.4 Running a Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4.2 Connection Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.2.1 Opening Handshake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.2.2 Connection Open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.3 Closing a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.4 Connection Close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.3 Creating Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3.1 Client Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3.2 Running a Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4.4 WebSocket Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.4.1 Common Options (server and client) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.4.2 Server-Only Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.4.3 Client-Only Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

4.5 Upgrading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.5.1 From < 0.7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

5 WAMP Programming 315.1 Application Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

5.1.1 Creating Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325.1.2 Running Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335.1.3 Running Subclass-Style Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335.1.4 Patterns for More Complicated Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 345.1.5 Longer Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

5.2 Component Configuration Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.2.1 transports= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.2.2 realm= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395.2.3 session_factory= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395.2.4 authentication= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5.3 Running a WAMP Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.4 Remote Procedure Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

5.4.1 Registering Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.4.2 Calling Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5.5 Publish & Subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425.5.1 Subscribing to Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435.5.2 Publishing Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

5.6 Session Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.7 Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465.8 Upgrading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

5.8.1 From < 0.8.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475.8.2 From < 0.9.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

6 XBR Programming 496.1 On-chain XBR smart contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

6.1.1 SimpleBlockchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506.1.2 SimpleBlockchain Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506.1.3 Using the ABI files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516.1.4 Data stored on-chain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

6.2 Off-chain XBR market maker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526.2.1 SimpleBuyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526.2.2 SimpleBuyer Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526.2.3 SimpleSeller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

ii

Page 5: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

6.2.4 SimpleSeller Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536.2.5 KeySeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

6.3 Interface Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546.3.1 IMarketMaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546.3.2 IProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546.3.3 IConsumer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546.3.4 ISeller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546.3.5 IBuyer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

7 WebSocket Examples 557.1 Basic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

7.1.1 Echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.1.2 Slow Square . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557.1.3 Testee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

7.2 Additional Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.1 Secure WebSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.2 WebSocket and Twisted Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.3 Twisted Web, WebSocket and WSGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.4 Secure WebSocket and Twisted Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.5 WebSocket Ping-Pong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567.2.6 More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

8 WAMP Examples 598.1 Overview of Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598.2 Automatically Run All Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608.3 Publish & Subscribe (PubSub) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608.4 Remote Procedure Calls (RPC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608.5 I’m Confused, Just Tell Me What To Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

9 API Reference 619.1 Module autobahn.util . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619.2 Module autobahn.websocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

9.2.1 WebSocket Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669.2.2 WebSocket Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729.2.3 WebSocket Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759.2.4 WebSocket Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

9.3 Module autobahn.rawsocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799.3.1 RawSocket Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

9.4 Module autobahn.wamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809.4.1 WAMP Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809.4.2 WAMP Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879.4.3 WAMP Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949.4.4 WAMP Authentication and Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

9.5 Module autobahn.wamp.component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989.5.1 Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

9.6 Module autobahn.twisted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999.6.1 Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009.6.2 WebSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019.6.3 WAMP-over-WebSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . 1029.6.4 WAMP-over-RawSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . 1029.6.5 WAMP Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

9.7 Module autobahn.asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1059.7.1 Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1059.7.2 WebSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

iii

Page 6: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

9.7.3 WAMP-over-WebSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . 1079.7.4 WAMP-over-RawSocket Protocols and Factories . . . . . . . . . . . . . . . . . . . . . . . 1089.7.5 WAMP Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

10 Changelog 11110.1 19.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11110.2 19.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11110.3 19.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11110.4 19.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11110.5 19.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.6 19.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.7 19.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.8 19.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.9 19.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.10 19.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11210.11 19.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.12 19.3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.13 19.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.14 19.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.15 19.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.16 18.12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.17 18.11.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.18 18.11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.19 18.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11410.20 18.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.21 18.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.22 18.8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.23 18.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.24 18.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.25 18.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11510.26 18.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.27 18.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.28 18.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.29 18.3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.30 17.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11610.31 17.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.32 17.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.33 17.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.34 17.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.35 17.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.36 17.6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11710.37 17.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11810.38 17.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11810.39 0.18.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11810.40 0.18.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11810.41 0.18.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11910.42 0.17.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11910.43 0.17.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11910.44 0.17.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11910.45 0.16.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12010.46 0.16.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12010.47 0.15.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12010.48 0.14.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12010.49 0.14.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

iv

Page 7: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

10.50 0.13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12110.51 0.13.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12110.52 0.12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12110.53 0.11.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.54 0.10.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.55 0.10.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.56 0.10.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.57 0.10.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12210.58 0.10.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.59 0.10.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.60 0.10.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.61 0.10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.62 0.10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.63 0.10.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12410.64 0.9.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12410.65 0.9.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12410.66 0.9.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12410.67 0.9.3-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12510.68 0.9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12510.69 0.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12510.70 0.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12510.71 0.9.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12510.72 0.8.15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12610.73 0.8.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12610.74 0.8.13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12610.75 0.8.12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12610.76 0.8.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12610.77 0.8.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.78 0.8.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.79 0.8.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.80 0.8.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.81 0.8.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.82 0.8.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12710.83 0.8.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.84 0.8.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.85 0.8.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.86 0.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.87 0.8.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12810.88 0.7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.89 0.7.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.90 0.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.91 0.7.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.92 0.7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.93 0.6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13010.94 0.6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13010.95 0.6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13010.96 0.5.14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

Python Module Index 133

Index 135

v

Page 8: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

vi

Page 9: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 1

Autobahn|Python

Open-source (MIT) real-time framework for Web, Mobile & Internet of Things.

Autobahn|Python is part of the Autobahn project and provides open-source implementations of

• The WebSocket Protocol

• The Web Application Messaging Protocol (WAMP)

in Python 2 and 3, running on Twisted or asyncio.

1.1 Autobahn Features

WebSocket allows bidirectional real-time messaging on the Web while WAMP provides applications with high-levelcommunication abstractions (remote procedure calling and publish/subscribe) in an open standard WebSocket-basedprotocol.

Autobahn|Python features:

• framework for WebSocket and WAMP clients

• compatible with Python 2.7 and 3.3+

• runs on CPython, PyPy and Jython

• runs under Twisted and asyncio

• implements WebSocket RFC6455 (and draft versions Hybi-10+)

• implements WebSocket compression

1

Page 10: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• implements WAMP, the Web Application Messaging Protocol

• supports TLS (secure WebSocket) and proxies

• Open-source (MIT license)

. . . and much more.

Further, Autobahn|Python is written with these goals:

1. high-performance, fully asynchronous and scalable code

2. best-in-class standards conformance and security

We do take those design and implementation goals quite serious. For example, Autobahn|Python has 100% strictpasses with AutobahnTestsuite, the quasi industry standard of WebSocket protocol test suites we originally createdonly to test Autobahn|Python ;)

For (hopefully) current test reports from the Testsuite see

• WebSocket client functionality

• WebSocket server functionality

Note: In the following, we will just refer to Autobahn instead of the more precise term Autobahn|Python and thereis no ambiguity.

1.2 What can I do with Autobahn?

WebSocket is great for apps like chat, trading, multi-player games or real-time charts. It allows you to activelypush information to clients as it happens. (See also Automatically Run All Examples)

Further, WebSocket allows you to real-time enable your Web user interfaces: always current information withoutreloads or polling. UIs no longer need to be a boring, static thing. Looking for the right communication technologyfor your next-generation Web apps? Enter WebSocket.

And WebSocket works great not only on the Web, but also as a protocol for wiring up the Internet-of-Things (IoT).Connecting a sensor or actor to other application components in real-time over an efficient protocol. Plus: you areusing the same protocol to connect frontends like Web browsers.

While WebSocket already is quite awesome, it is still low-level. Which is why we have WAMP. WAMP allows youto compose your application from loosely coupled components that talk in real-time with each other - using nicehigh-level communication patterns (“Remote Procedure Calls” and “Publish & Subscribe”).

WAMP enables application architectures with application code distributed freely across processes and devices ac-cording to functional aspects. Since WAMP implementations exist for multiple languages, WAMP applications can be

2 Chapter 1. Autobahn|Python

Page 11: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

polyglot. Application components can be implemented in a language and run on a device which best fit the particularuse case.

WAMP is a routed protocol, so you need a WAMP router. We suggest using Crossbar.io, but there are also otherimplementations available.

More:

• WebSocket - Why, what, and - can I use it?

• Why WAMP?

1.3 Show me some code!

A sample WebSocket server:

from autobahn.twisted.websocket import WebSocketServerProtocol# or: from autobahn.asyncio.websocket import WebSocketServerProtocol

class MyServerProtocol(WebSocketServerProtocol):

def onConnect(self, request):print("Client connecting: {}".format(request.peer))

def onOpen(self):print("WebSocket connection open.")

def onMessage(self, payload, isBinary):if isBinary:

print("Binary message received: {} bytes".format(len(payload)))else:

print("Text message received: {}".format(payload.decode('utf8')))

## echo back message verbatimself.sendMessage(payload, isBinary)

def onClose(self, wasClean, code, reason):print("WebSocket connection closed: {}".format(reason))

Complete example code:

• WebSocket Echo (Twisted-based)

• WebSocket Echo (Asyncio-based)

Introduction to WebSocket Programming with Autobahn:

• WebSocket Programming

A sample WAMP application component implementing all client roles:

from autobahn.twisted.component import Component# or: from autobahn.asyncio.component import Component

demo = Component(transports=[u"wss://demo.crossbar.io/ws"],

)

(continues on next page)

1.3. Show me some code! 3

Page 12: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

# 1. subscribe to a [email protected](u'com.myapp.hello')def hello(msg):

print("Got hello: {}".format(msg))

# 2. register a procedure for remote [email protected](u'com.myapp.add2')def add2(x, y):

return x + y

# 3. after we've authenticated, run some [email protected]_joinasync def joined(session, details):

# publish an event (won't go to "this" session by default)await session.publish('com.myapp.hello', 'Hello, world!')

# 4. call a remote procedureresult = await session.call('com.myapp.add2', 2, 3)print("com.myapp.add2(2, 3) = {}".format(result))

if __name__ == "__main__":run([demo])

Complete example code:

• Twisted Example

• asyncio Example

Introduction to WAMP Programming with Autobahn:

• WAMP Programming

1.4 Where to start

To get started, jump to Installation.

For developers new to asynchronous programming, Twisted or asyncio, we’ve collected some useful pointers andinformation in Asynchronous Programming.

For WebSocket developers, WebSocket Programming explains all you need to know about using Autobahn as aWebSocket library, and includes a full reference for the relevant parts of the API.

WebSocket Examples lists WebSocket code examples covering a broader range of uses cases and advanced WebSocketfeatures.

For WAMP developers, WAMP Programming gives an introduction for programming with WAMP in Python usingAutobahn.

WAMP Examples lists WAMP code examples covering all features of WAMP.

1.5 Get in touch

Development of Autobahn takes place on the GitHub source repository.

4 Chapter 1. Autobahn|Python

Page 13: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Note: We are open for contributions, whether that’s code or documentation! Preferably via pull requests.

We also take bug reports at the issue tracker.

The best place to ask questions is on the mailing list. We’d also love to hear about your project and what you areusing Autobahn for!

Another option is StackOverflow where questions related to Autobahn are tagged “autobahn” (or “autobahnws”).

The best way to Search the Web for related material is by using these (base) search terms:

• “autobahnpython”

• “autobahnws”

You can also reach users and developers on IRC channel #autobahn at freenode.net.

Finally, we are on Twitter.

1.6 Contributing

Autobahn is an open source project, and hosted on GitHub. The GitHub repository includes the documentation.

We’re looking for all kinds of contributions - from simple fixes of typos in the code or documentation to implementa-tion of new features and additions of tutorials.

If you want to contribute to the code or the documentation: we use the Fork & Pull Model.

This means that you fork the repo, make changes to your fork, and then make a pull request here on the main repo.

This article on GitHub gives more detailed information on how the process works.

In order to run the unit-tests, we use Tox to build the various test-environments. To run them all, simply run tox fromthe top-level directory of the clone.

For test-coverage, see the Makefile target test_coverage, which deletes the coverage data and then runs the testsuite with various tox test-environments before outputting HTML annotated coverage to ./htmlcov/index.htmland a coverage report to the terminal.

There are two environment variables the tests use: USE_TWISTED=1 or USE_ASYNCIO=1 control whether to rununit-tests that are specific to one framework or the other.

See tox.ini for details on how to run in the different environments.

1.7 Release Testing

Before pushing a new release, three levels of tests need to pass:

1. the unit tests (see above)

2. the [WebSocket level tests](wstest/README.md)

3. the [WAMP level tests](examples/README.md) (*)

> (*): these will launch a Crossbar.io router for testing

1.6. Contributing 5

Page 14: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

1.8 Sitemap

Please see Site Contents for a full site-map.

6 Chapter 1. Autobahn|Python

Page 15: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 2

Installation

This document describes the prerequisites and the installation of Autobahn.

2.1 Requirements

Autobahn runs on Python on top of these networking frameworks:

• Twisted

• asyncio

You will need at least one of those.

Note: Most of Autobahn’s WebSocket and WAMP features are available on both Twisted and asyncio, so you are freeto choose the underlying networking framework based on your own criteria.

For Twisted installation, please see here. Asyncio comes bundled with Python 3.4+. For Python 3.3, install it fromhere. For Python 2, trollius will work.

2.1.1 Supported Configurations

Here are the configurations supported by Autobahn:

Python Twisted asyncio NotesCPython 2.7 yes yes asyncio support via trolliusCPython 3.3 yes yes asyncio support via tulipCPython 3.4+ yes yes asyncio in the standard libraryPyPy 2.2+ yes yes asyncio support via trolliusJython 2.7+ yes ? Issues: 1, 2

7

Page 16: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

2.1.2 Performance Note

Autobahn is portable, well tuned code. You can further accelerate performance by

• Running under PyPy (recommended!) or

• on CPython, install the native accelerators wsaccel and ujson (you can use the install variant accelerationfor that - see below)

To give you an idea of the performance you can expect, here is a blog post benchmarking Autobahn running on theRaspberryPi (a tiny embedded computer) under PyPy.

2.2 Installing Autobahn

2.2.1 Using Docker

We offer Docker Images with Autobahn pre-installed. To use this, if you have Docker already installed, just do

sudo docker run -it crossbario/autobahn-python:cpy2 python client.py--url ws://IP _of_WAMP_router:8080/ws --realm realm1

This starts up a Docker container and client.py, which connects to a Crossbar.io router at the given URL and to thegiven realm.

There are several docker images to choose from, depending on whether you are using Python 2, 3 or PyPy (Python 2only for now).

There are the flavors which are based on the official Python 2, 3 and PyPy images, plus Python 2 and 3 versions usingAlpine Linux, which have a smaller footprint. (Note: Footprint only matters for the download once per machine, afterthat the cached image is used. Containers off the same image/layers only take up space corresponding to how differentfrom the image they are, so image size is relatively less important when using multiple containers.)

2.2.2 Install from PyPI

To install Autobahn from the Python Package Index using Pip

pip install autobahn

You can also specify install variants (see below). E.g. to install Twisted automatically as a dependency

pip install autobahn[twisted]

And to install asyncio backports automatically when required

pip install autobahn[asyncio]

2.2.3 Install from Sources

To install from sources, clone the repository:

git clone [email protected]:crossbario/autobahn-python.git

checkout a tagged release:

8 Chapter 2. Installation

Page 17: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

cd AutobahnPythongit checkout v0.9.1

Warning: You should only use tagged releases, not master. The latest code from master might be broken,unfinished and untested. So you have been warned ;)

Then do:

cd autobahnpython setup.py install

You can also use pip for the last step, which allows to specify install variants (see below)

pip install -e .[twisted]

2.2.4 Install Variants

Autobahn has the following install variants:

Variant Descriptiontwisted Install Twisted as a dependencyasyncio Install asyncio as a dependency (or use stdlib)accelerate Install native acceleration packages on CPythoncompress Install packages for non-standard WebSocket compression methodsserialization Install packages for additional WAMP serialization formats (currently MsgPack)

Install variants can be combined, e.g. to install Autobahn with all optional packages for use with Twisted on CPython:

pip install autobahn[twisted,accelerate,compress,serialization]

2.2.5 Windows Installation

For convenience, here are minimal instructions to install both Python and Autobahn/Twisted on Windows:

1. Go to the Python web site and install Python 2.7 32-Bit

2. Add C:\Python27;C:\Python27\Scripts; to your PATH

3. Download the Pip install script and double click it (or run python get-pip.py from a command shell)

4. Open a command shell and run pip install autobahn[twisted]

2.3 Check the Installation

To check the installation, fire up the Python and run

>>> from autobahn import __version__>>> print(__version__)0.9.1

2.3. Check the Installation 9

Page 18: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

2.4 Depending on Autobahn

To require Autobahn as a dependency of your package, include the following in your setup.py script

install_requires = ["autobahn>=0.9.1"]

You can also depend on an install variant which automatically installs dependent packages

install_requires = ["autobahn[twisted]>=0.9.1"]

The latter will automatically install Twisted as a dependency.

Where to go

Now you’ve got Autobahn installed, depending on your needs, head over to

• Asynchronous Programming - An very short introduction plus pointers to good Web resources.

• WebSocket Programming - A guide to programming WebSocket applications with Autobahn

• WAMP Programming - A guide to programming WAMP applications with Autobahn

10 Chapter 2. Installation

Page 19: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 3

Asynchronous Programming

3.1 Introduction

3.1.1 The asynchronous programming approach

Autobahn is written according to a programming paradigm called asynchronous programming (or event driven pro-gramming) and implemented using non-blocking execution - and both go hand in hand.

A very good technical introduction to these concepts can be found in this chapter of an “Introduction to AsynchronousProgramming and Twisted”.

Here are two more presentations that introduce event-driven programming in Python

• Alex Martelli - Don’t call us, we’ll call you: callback patterns and idioms

• Glyph Lefkowitz - So Easy You Can Even Do It in JavaScript: Event-Driven Architecture for Regular Program-mers

Another highly recommended reading is The Reactive Manifesto which describes guiding principles, motivations andconnects the dots

Non-blocking means the ability to make continuous progress in order for the application to be responsiveat all times, even under failure and burst scenarios. For this all resources needed for a response—forexample CPU, memory and network—must not be monopolized. As such it can enable both lower latency,higher throughput and better scalability.

—The Reactive Manifesto

The fact that Autobahn is implemented using asynchronous programming and non-blocking execution shouldn’t comeas a surprise, since both Twisted and asyncio - the foundations upon which Autobahn runs - are asynchronous networkprogramming frameworks.

On the other hand, the principles of asynchronous programming are independent of Twisted and asyncio. For example,other frameworks that fall into the same category are:

• NodeJS

11

Page 20: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• Boost/ASIO

• Netty

• Tornado

• React

Tip: While getting accustomed to the asynchronous way of thinking takes some time and effort, the knowledge andexperience acquired can be translated more or less directly to other frameworks in the asynchronous category.

3.1.2 Other forms of Concurrency

Asynchronous programming is not the only approach to concurrency. Other styles of concurrency include

1. OS Threads

2. Green Threads

3. Actors

4. Software Transactional Memory (STM)

Obviously, we cannot go into much detail with all of above. But here are some pointers for further reading if you wantto compare and contrast asynchronous programming with other approaches.

With the Actor model a system is composed of a set of actors which are independently running, executing sequentiallyand communicate strictly by message passing. There is no shared state at all. This approach is used in systems like

• Erlang

• Akka

• Rust

• C++ Actor Framework

Software Transactional Memory (STM) applies the concept of Optimistic Concurrency Control from the persistentdatabase world to (transient) program memory. Instead of lettings programs directly modify memory, all operationsare first logged (inside a transaction), and then applied atomically - but only if no conflicting transaction has committedin the meantime. Hence, it’s “optimistic” in that it assumes to be able to commit “normally”, but needs to handle thefailing at commit time.

Green Threads is using light-weight, run-time level threads and thread scheduling instead of OS threads. Other thanthat, systems are implemented similar: green threads still block, and still do share state. Python has multiple efforts inthis category:

• Eventlet

• Gevent

• Stackless

3.1.3 Twisted or asyncio?

Since Autobahn runs on both Twisted and asyncio, which networking framework should you use?

Even more so, as the core of Twisted and asyncio is very similar and relies on the same concepts:

12 Chapter 3. Asynchronous Programming

Page 21: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Twisted asyncio DescriptionDeferred Future abstraction of a value which isn’t available yetReactor Event Loop waits for and dispatches eventsTransport Transport abstraction of a communication channel (stream or datagram)Protocol Protocol this is where actual networking protocols are implementedProtocol Factory Protocol Factory responsible for creating protocol instances

In fact, I’d say the biggest difference between Twisted and asyncio is Deferred vs Future. Although similar onsurface, their semantics are different. Deferred supports the concept of chainable callbacks (which can mutate thereturn values), and separate error-backs (which can cancel errors). Future has just a callback, that always gets asingle argument: the Future.

Also, asyncio is opinionated towards co-routines. This means idiomatic user code for asyncio is expected to useco-routines, and not plain Futures (which are considered too low-level for application code).

But anyway, with asyncio being part of the language standard library (since Python 3.4), wouldn’t you just always useasyncio? At least if you don’t have a need to support already existing Twisted based code.

The truth is that while the core of Twisted and asyncio are very similar, Twisted has a much broader scope: Twistedis “batteries included” for network programming.

So you get tons of actual network protocols already out-of-the-box - in production quality implementations!

asyncio does not include any actual application layer network protocols like HTTP. If you need those, you’ll have tolook for asyncio implementations outside the standard library. For example, here is a HTTP server and client libraryfor asyncio.

Over time, an ecosystem of protocols will likely emerge around asyncio also. But right now, Twisted has a bigadvantage here.

If you want to read more on this, Glyph (Twisted original author) has a nice blog post here.

3.2 Resources

Below we are listing a couple of resources on the Web for Twisted and asyncio that you may find useful.

3.2.1 Twisted Resources

We cannot give an introduction to asynchronous programming with Twisted here. And there is no need to, since thereis lots of great stuff on the Web. In particular we’d like to recommend the following resources.

If you have limited time and nevertheless want to have an in-depth view of Twisted, Jessica McKellar has a greatpresentation recording with Architecting an event-driven networking engine: Twisted Python. That’s 45 minutes.Highly recommended.

If you really want to get it, Dave Peticolas has written an awesome Introduction to Asynchronous Programming andTwisted. This is a detailed, hands-on tutorial with lots of code examples that will take some time to work through -but you actually learn how to program with Twisted.

Then of course there is

• The Twisted Documentation

• The Twisted API Reference

and lots and lots of awesome Twisted talks on PyVideo.

3.2. Resources 13

Page 22: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

3.2.2 Asyncio Resources

asyncio is very new (August 2014). So the amount of material on the Web is still limited. Here are some resourcesyou may find useful:

• Guido van Rossum’s Keynote at PyCon US 2013

• Tulip: Async I/O for Python 3

• Python 3.4 docs - asyncio

• PEP-3156 - Asynchronous IO Support Rebooted

• OSB 2015 - How Do Python Coroutines Work? - A. Jesse Jiryu Davis

However, we quickly introduce core asynchronous programming primitives provided by Twisted and asyncio:

3.3 Asynchronous Programming Primitives

In this section, we have a quick look at some of the asynchronous programming primitive provided by Twisted andasyncio to show similarities and differences.

3.3.1 Twisted Deferreds and inlineCallbacks

Documentation pointers:

• Introduction to Deferreds

• Deferreds Reference

• Twisted inlineCallbacks

Programming with Twisted Deferreds involves attaching callbacks to Deferreds which get called when the Deferredfinally either resolves successfully or fails with an error

d = some_function() # returns a Twisted Deferred ..

def on_success(res):print("result: {}".format(res))

def on_error(err):print("error: {}".format(err))

d.addCallbacks(on_success, on_error)

Using Deferreds offers the greatest flexibility since you are able to pass around Deferreds freely and can run codeconcurrently.

However, using plain Deferreds comes at a price: code in this style looks very different from synchronous/blockingcode and the code can become hard to follow.

Now, Twisted inlineCallbacks let you write code in a sequential looking manner that nevertheless executes asyn-chronously and non-blocking under the hood.

So converting above snipped to inlineCallbacks the code will look like

14 Chapter 3. Asynchronous Programming

Page 23: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

try:res = yield some_function()print("result: {}".format(res))

except Exception as err:print("error: {}".format(err))

As you can see, this code looks very similar to regular synchronous/blocking Python code. The only difference (onsurface) is the use of yield when calling a function that runs asynchronously. Otherwise, you process success resultvalues and exceptions exactly as with regular code.

Note: We’ll only show basic usage here - for a more basic and complete introduction, please have a look at thischapter from this tutorial.

Example

The following demonstrates basic usage of inlineCallbacks in a complete example you can run.

First, consider this program using Deferreds. We simulate calling a slow function by sleeping (without blocking)inside the function slow_square

1 from twisted.internet import reactor2 from twisted.internet.defer import Deferred3

4 def slow_square(x):5 d = Deferred()6

7 def resolve():8 d.callback(x * x)9

10 reactor.callLater(1, resolve)11 return d12

13 def test():14 d = slow_square(3)15

16 def on_success(res):17 print(res)18 reactor.stop()19

20 d.addCallback(on_success)21

22 test()23 reactor.run()

This is just regular Twisted code - nothing exciting here:

1. We create a Deferred to be returned by our slow_square function (line 5)

2. We create a function resolve (a closure) in which we resolve the previously created Deferred with the result(lines 7-8)

3. Then we ask the Twisted reactor to call resolve after 1 second (line 10)

4. And we return the previously created Deferred to the caller (line 11)

What you can see even with this trivial example already is that the code looks quite differently from syn-chronous/blocking code. It needs some practice until such code becomes natural to read.

3.3. Asynchronous Programming Primitives 15

Page 24: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Now, when converted to inlineCallbacks, the code becomes:

1 from twisted.internet import reactor2 from twisted.internet.defer import inlineCallbacks, returnValue3 from autobahn.twisted.util import sleep4

5 @inlineCallbacks6 def slow_square(x):7 yield sleep(1)8 returnValue(x * x)9

10 @inlineCallbacks11 def test():12 res = yield slow_square(3)13 print(res)14 reactor.stop()15

16 test()17 reactor.run()

Have a look at the highlighted lines - here is what we do:

1. Decorating our squaring function with inlineCallbacks (line 5). Doing so marks the function as a corou-tine which allows us to use this sequential looking coding style.

2. Inside the function, we simulate the slow execution by sleeping for a second (line 7). However, we are sleepingin a non-blocking way (autobahn.twisted.util.sleep()). The yield will put the coroutine asideuntil the sleep returns.

3. To return values from Twisted coroutines, we need to use returnValue (line 8).

Note: The reason returnValue is necessary goes deep into implementation details of Twisted and Python. In short:co-routines in Python 2 with Twisted are simulated using exceptions. Only Python 3.3+ has gotten native support forco-routines using the new yield from statement, Python 3.5+ use await statement and it is the new recommendedmethod.

In above, we are using a little helper autobahn.twisted.util.sleep() for sleeping “inline”. The helper isreally trivial:

from twisted.internet import reactorfrom twisted.internet.defer import Deferred

def sleep(delay):d = Deferred()reactor.callLater(delay, d.callback, None)return d

The rest of the program is just for driving our test function and running a Twisted reactor.

3.3.2 Asyncio Futures and Coroutines

Asyncio Futures like Twisted Deferreds encapsulate the result of a future computation. At the time of creation, theresult is (usually) not yet available, and will only be available eventually.

On the other hand, asyncio futures are quite different from Twisted Deferreds. One difference is that they have nobuilt-in machinery for chaining.

16 Chapter 3. Asynchronous Programming

Page 25: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Asyncio Coroutines are (on a certain level) quite similar to Twisted inline callbacks. Here is the code correspondingto our example above:

Example

The following demonstrates basic usage of asyncio.coroutine in a complete example you can run.

First, consider this program using plain asyncio.Future. We simulate calling a slow function by sleeping (withoutblocking) inside the function slow_square

1 import asyncio2

3 def slow_square(x):4 f = asyncio.Future()5

6 def resolve():7 f.set_result(x * x)8

9 loop = asyncio.get_event_loop()10 loop.call_later(1, resolve)11

12 return f13

14 def test():15 f = slow_square(3)16

17 def done(f):18 res = f.result()19 print(res)20

21 f.add_done_callback(done)22

23 return f24

25 loop = asyncio.get_event_loop()26 loop.run_until_complete(test())27 loop.close()

Using asyncio in this way is probably quite unusual. This is because asyncio is opinionated towards using coroutinesfrom the beginning. Anyway, here is what above code does:

1. We create a Future to be returned by our slow_square function (line 4)

2. We create a function resolve (a closure) in which we resolve the previously created Future with the result(lines 6-7)

3. Then we ask the asyncio event loop to call resolve after 1 second (line 10)

4. And we return the previously created Future to the caller (line 12)

What you can see even with this trivial example already is that the code looks quite differently from syn-chronous/blocking code. It needs some practice until such code becomes natural to read.

Now, when converted to asyncio.coroutine, the code becomes:

1 import asyncio2

3 async def slow_square(x):4 await asyncio.sleep(1)

(continues on next page)

3.3. Asynchronous Programming Primitives 17

Page 26: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

5 return x * x6

7

8 async def test():9 res = await slow_square(3)

10 print(res)11

12 loop = asyncio.get_event_loop()13 loop.run_until_complete(test())

The main differences (on surface) are:

1. The declaration of the function with async keyword (line 3) in asyncio versus the decorator @defer.inlineCallbacks with Twisted

2. The use of defer.returnValue in Twisted for returning values whereas in asyncio, you can use plainreturns (line 6)

3. The use of await in asyncio, versus yield in Twisted (line 5)

4. The auxiliary code to get the event loop started and stopped

Most of the examples that follow will show code for both Twisted and asyncio, unless the conversion is trivial.

18 Chapter 3. Asynchronous Programming

Page 27: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 4

WebSocket Programming

This guide introduces WebSocket programming with Autobahn.

You’ll see how to create WebSocket server (“Creating Servers”) and client applications (“Creating Clients”).

Resources:

• Example Code for this Guide: Twisted-based or asyncio-based

• More WebSocket Examples

4.1 Creating Servers

Using Autobahn you can create WebSocket servers that will be able to talk to any (compliant) WebSocket client,including browsers.

We’ll cover how to define the behavior of your WebSocket server by writing protocol classes and show some boiler-plate for actually running a WebSocket server using the behavior defined in the server protocol.

4.1.1 Server Protocols

To create a WebSocket server, you need to write a protocol class to specify the behavior of the server.

For example, here is a protocol class for a WebSocket echo server that will simply echo back any WebSocket messageit receives:

class MyServerProtocol(WebSocketServerProtocol):

def onMessage(self, payload, isBinary):## echo back message verbatimself.sendMessage(payload, isBinary)

This is just three lines of code, but we will go through each one carefully, since writing protocol classes like abovereally is core to WebSocket programming using Autobahn.

19

Page 28: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

The first thing to note is that you derive your protocol class from a base class provided by Autobahn. Depending onwhether you write a Twisted or a asyncio based application, here are the base classes to derive from:

• autobahn.twisted.websocket.WebSocketServerProtocol

• autobahn.asyncio.websocket.WebSocketServerProtocol

So a Twisted-based echo protocol would import the base protocol from autobahn.twisted.websocket andderive from autobahn.twisted.websocket.WebSocketServerProtocol

Twisted:

from autobahn.twisted.websocket import WebSocketServerProtocol

class MyServerProtocol(WebSocketServerProtocol):

def onMessage(self, payload, isBinary):## echo back message verbatimself.sendMessage(payload, isBinary)

while an asyncio echo protocol would import the base protocol from autobahn.asyncio.websocket and derivefrom autobahn.asyncio.websocket.WebSocketServerProtocol

asyncio:

from autobahn.asyncio.websocket import WebSocketServerProtocol

class MyServerProtocol(WebSocketServerProtocol):

def onMessage(self, payload, isBinary):## echo back message verbatimself.sendMessage(payload, isBinary)

Note: In this example, only the imports differ between the Twisted and the asyncio variant. The rest of the code isidentical. However, in most real world programs you probably won’t be able to or don’t want to avoid using networkframework specific code.

4.1.2 Receiving Messages

The second thing to note is that we override a callback onMessage which is called by Autobahn whenever thecallback related event happens.

In case of onMessage, the callback will be called whenever a new WebSocket message was received. There aremore WebSocket related callbacks, but for now the onMessage callback is all we need.

When our server receives a WebSocket message, the autobahn.websocket.interfaces.IWebSocketChannel.onMessage() will fire with the message payload received.

The payload is always a Python byte string. Since WebSocket is able to transmit text (UTF8) and binary payload,the actual payload type is signaled via the isBinary flag.

When the payload is text (isBinary == False), the bytes received will be an UTF8 encoded string. To processtext payloads, the first thing you often will do is decoding the UTF8 payload into a Python string:

s = payload.decode('utf8')

20 Chapter 4. WebSocket Programming

Page 29: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Tip: You don’t need to validate the bytes for actually being valid UTF8 - Autobahn does that already when receivingthe message.

When using WebSocket text messages with JSON payload, typical code for receiving and decoding messages intoPython objects that works on both Python 2 and 3 would look like this:

import jsonobj = json.loads(payload.decode('utf8'))

We are using the Python standard JSON module json.

The payload (which is of type bytes on Python 3 and str on Python 2) is decoded from UTF8 into a nativePython string, and then parsed from JSON into a native Python object.

4.1.3 Sending Messages

The third thing to note is that we use methods like sendMessage provided by the base class to perform WebSocketrelated actions, like sending a WebSocket message.

As there are more methods for performing other actions (like closing the connection), we’ll come back to this later,but for now, the sendMessage method is all we need.

autobahn.websocket.interfaces.IWebSocketChannel.sendMessage() takes the payload tosend in a WebSocket message as Python bytes. Since WebSocket is able to transmit payloads of text (UTF8) andbinary type, you need to tell Autobahn the actual type of the payload bytes. This is done using the isBinary flag.

Hence, to send a WebSocket text message, you will usually encode the payload to UTF8:

payload = s.encode('utf8')self.sendMessage(payload, isBinary = False)

Warning: Autobahn will NOT validate the bytes of a text payload being sent for actually being valid UTF8.You MUST ensure that you only provide valid UTF8 when sending text messages. If you produce invalid UTF8, aconforming WebSocket peer will close the WebSocket connection due to the protocol violation.

When using WebSocket text messages with JSON payload, typical code for encoding and sending Python objectsthat works on both Python 2 and 3 would look like this:

import jsonpayload = json.dumps(obj, ensure_ascii = False).encode('utf8')

We are using the Python standard JSON module json.

The ensure_ascii == False option allows the JSON serializer to use Unicode strings. We can do this sincewe are encoding to UTF8 afterwards anyway. And UTF8 can represent the full Unicode character set.

4.1. Creating Servers 21

Page 30: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

4.1.4 Running a Server

Now that we have defined the behavior of our WebSocket server in a protocol class, we need to actually start a serverbased on that behavior.

Doing so involves two steps:

1. Create a Factory for producing instances of our protocol class

2. Create a TCP listening server using the former Factory

Here is one way of doing that when using Twisted

Twisted:

if __name__ == '__main__':

import sys

from twisted.python import logfrom twisted.internet import reactorlog.startLogging(sys.stdout)

from autobahn.twisted.websocket import WebSocketServerFactoryfactory = WebSocketServerFactory()factory.protocol = MyServerProtocol

reactor.listenTCP(9000, factory)reactor.run()

What we are doing here is

1. Setup Twisted logging

2. Create a autobahn.twisted.websocket.WebSocketServerFactory and set ourMyServerProtocol on the factory (the highlighted lines)

3. Start a server using the factory, listening on TCP port 9000

Similar, here is the asyncio way

asyncio:

if __name__ == '__main__':

try:import asyncio

except ImportError:## Trollius >= 0.3 was renamedimport trollius as asyncio

from autobahn.asyncio.websocket import WebSocketServerFactoryfactory = WebSocketServerFactory()factory.protocol = MyServerProtocol

loop = asyncio.get_event_loop()coro = loop.create_server(factory, '127.0.0.1', 9000)server = loop.run_until_complete(coro)

try:loop.run_forever()

(continues on next page)

22 Chapter 4. WebSocket Programming

Page 31: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

except KeyboardInterrupt:pass

finally:server.close()loop.close()

What we are doing here is

1. Import asyncio, or the Trollius backport

2. Create a autobahn.asyncio.websocket.WebSocketServerFactory and set ourMyServerProtocol on the factory (the highlighted lines)

3. Start a server using the factory, listening on TCP port 9000

Note: As can be seen, the boilerplate to create and run a server differ from Twisted, but the core code of creating afactory and setting our protocol (the highlighted lines) is identical (other than the differing import for the WebSocketfactory).

You can find complete code for above examples here:

• WebSocket Echo (Twisted-based)

• WebSocket Echo (Asyncio-based)

4.2 Connection Lifecycle

As we have seen above, Autobahn will fire callbacks on your protocol class whenever the event related to the respectivecallback occurs.

It is in these callbacks that you will implement application specific code.

The core WebSocket interface autobahn.websocket.interfaces.IWebSocketChannel provides the fol-lowing callbacks:

• autobahn.websocket.interfaces.IWebSocketChannel.onConnect()

• autobahn.websocket.interfaces.IWebSocketChannel.onConnecting()

• autobahn.websocket.interfaces.IWebSocketChannel.onOpen()

• autobahn.websocket.interfaces.IWebSocketChannel.onMessage()

• autobahn.websocket.interfaces.IWebSocketChannel.onClose()

We have already seen the callback for Receiving Messages. This callback will usually fire many times during thelifetime of a WebSocket connection.

In contrast, the other four callbacks above each only fires once for a given connection.

4.2.1 Opening Handshake

Whenever a new client connects to the server, a new protocol instance will be created and the autobahn.websocket.interfaces.IWebSocketChannel.onConnect() callback fires as soon as the WebSocketopening handshake is begun by the client.

4.2. Connection Lifecycle 23

Page 32: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

For a WebSocket server protocol, onConnect() will fire with autobahn.websocket.protocol.ConnectionRequest providing information on the client wishing to connect via WebSocket.

class MyServerProtocol(WebSocketServerProtocol):

def onConnect(self, request):print("Client connecting: {}".format(request.peer))

For a WebSocket client protocol, onConnecting() is called immediately before the handshake to the server starts.It is called with some details about the underlying transport. This may return None (the default) to get defaultvalues for several options (which are gotten from the Factory) or it may return a autobahn.websocket.types.ConnectingRequest instance to indicate options for this handshake. This allows using different options on eachrequest (as opposed to using a static set of options in the Factory).

Then, once the server has responded, a WebSocket client protocol will fire onConnect() with a autobahn.websocket.protocol.ConnectionResponse providing information on the WebSocket connection that wasaccepted by the server.

class MyClientProtocol(WebSocketClientProtocol):

def onConnect(self, response):print("Connected to Server: {}".format(response.peer))

In this callback you can do things like

• checking or setting cookies or other HTTP headers

• verifying the client IP address

• checking the origin of the WebSocket request

• negotiate WebSocket subprotocols

For example, a WebSocket client might offer to speak several WebSocket subprotocols. The server can inspectthe offered protocols in onConnect() via the supplied instance of autobahn.websocket.protocol.ConnectionRequest. When the server accepts the client, it’ll chose one of the offered subprotocols. The clientcan then inspect the selected subprotocol in it’s onConnect() callback in the supplied instance of autobahn.websocket.protocol.ConnectionResponse.

4.2.2 Connection Open

The autobahn.websocket.interfaces.IWebSocketChannel.onOpen() callback fires when the Web-Socket opening handshake has been successfully completed. You now can send and receive messages over the con-nection.

class MyProtocol(WebSocketProtocol):

def onOpen(self):print("WebSocket connection open.")

4.2.3 Closing a Connection

The core WebSocket interface autobahn.websocket.interfaces.IWebSocketChannel provides the fol-lowing methods:

• autobahn.websocket.interfaces.IWebSocketChannel.sendMessage()

24 Chapter 4. WebSocket Programming

Page 33: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• autobahn.websocket.interfaces.IWebSocketChannel.sendClose()

We’ve already seen one of above in Sending Messages.

The autobahn.websocket.interfaces.IWebSocketChannel.sendClose() will initiate a Web-Socket closing handshake. After starting to close a WebSocket connection, no messages can be sent. Eventually,the autobahn.websocket.interfaces.IWebSocketChannel.onClose() callback will fire.

After a WebSocket connection has been closed, the protocol instance will get recycled. Should the client reconnect, anew protocol instance will be created and a new WebSocket opening handshake performed.

4.2.4 Connection Close

When the WebSocket connection has closed, the autobahn.websocket.interfaces.IWebSocketChannel.onClose() callback fires.

class MyProtocol(WebSocketProtocol):

def onClose(self, wasClean, code, reason):print("WebSocket connection closed: {}".format(reason))

When the connection has closed, no messages will be received anymore and you cannot send messages also. Theprotocol instance won’t be reused. It’ll be garbage collected. When the client reconnects, a completely new protocolinstance will be created.

4.3 Creating Clients

Note: Creating WebSocket clients using Autobahn works very similar to creating WebSocket servers. Hence youshould have read through Creating Servers first.

As with servers, the behavior of your WebSocket client is defined by writing a protocol class.

4.3.1 Client Protocols

To create a WebSocket client, you need to write a protocol class to specify the behavior of the client.

For example, here is a protocol class for a WebSocket client that will send a WebSocket text message as soon as it isconnected and log any WebSocket messages it receives:

class MyClientProtocol(WebSocketClientProtocol):

def onOpen(self):self.sendMessage(u"Hello, world!".encode('utf8'))

def onMessage(self, payload, isBinary):if isBinary:

print("Binary message received: {0} bytes".format(len(payload)))else:

print("Text message received: {0}".format(payload.decode('utf8')))

Similar to WebSocket servers, you derive your WebSocket client protocol class from a base class provided by Auto-bahn. Depending on whether you write a Twisted or a asyncio based application, here are the base classes to derivefrom:

4.3. Creating Clients 25

Page 34: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• autobahn.twisted.websocket.WebSocketClientProtocol

• autobahn.asyncio.websocket.WebSocketClientProtocol

So a Twisted-based protocol would import the base protocol from autobahn.twisted.websocket and derivefrom autobahn.twisted.websocket.WebSocketClientProtocol

Twisted:

from autobahn.twisted.websocket import WebSocketClientProtocol

class MyClientProtocol(WebSocketClientProtocol):

def onOpen(self):self.sendMessage(u"Hello, world!".encode('utf8'))

def onMessage(self, payload, isBinary):if isBinary:

print("Binary message received: {0} bytes".format(len(payload)))else:

print("Text message received: {0}".format(payload.decode('utf8')))

while an asyncio-based protocol would import the base protocol from autobahn.asyncio.websocket andderive from autobahn.asyncio.websocket.WebSocketClientProtocol

asyncio:

from autobahn.asyncio.websocket import WebSocketClientProtocol

class MyClientProtocol(WebSocketClientProtocol):

def onOpen(self):self.sendMessage(u"Hello, world!".encode('utf8'))

def onMessage(self, payload, isBinary):if isBinary:

print("Binary message received: {0} bytes".format(len(payload)))else:

print("Text message received: {0}".format(payload.decode('utf8')))

Note: In this example, only the imports differs between the Twisted and the asyncio variant. The rest of the code isidentical. However, in most real world programs you probably won’t be able to or don’t want to avoid using networkframework specific code.

Receiving and sending WebSocket messages as well as connection lifecycle in clients works exactly the same as withservers. Please see

• Receiving Messages

• Sending Messages

• Connection Lifecycle

4.3.2 Running a Client

Now that we have defined the behavior of our WebSocket client in a protocol class, we need to actually start a clientbased on that behavior.

26 Chapter 4. WebSocket Programming

Page 35: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Doing so involves two steps:

1. Create a Factory for producing instances of our protocol class

2. Create a TCP connecting client using the former Factory

Here is one way of doing that when using Twisted

Twisted:

if __name__ == '__main__':

import sys

from twisted.python import logfrom twisted.internet import reactorlog.startLogging(sys.stdout)

from autobahn.twisted.websocket import WebSocketClientFactoryfactory = WebSocketClientFactory()factory.protocol = MyClientProtocol

reactor.connectTCP("127.0.0.1", 9000, factory)reactor.run()

What we are doing here is

1. Setup Twisted logging

2. Create a autobahn.twisted.websocket.WebSocketClientFactory and set ourMyClientProtocol on the factory (the highlighted lines)

3. Start a client using the factory, connecting to localhost 127.0.0.1 on TCP port 9000

Similar, here is the asyncio way

asyncio:

if __name__ == '__main__':

try:import asyncio

except ImportError:## Trollius >= 0.3 was renamedimport trollius as asyncio

from autobahn.asyncio.websocket import WebSocketClientFactoryfactory = WebSocketClientFactory()factory.protocol = MyClientProtocol

loop = asyncio.get_event_loop()coro = loop.create_connection(factory, '127.0.0.1', 9000)loop.run_until_complete(coro)loop.run_forever()loop.close()

What we are doing here is

1. Import asyncio, or the Trollius backport

2. Create a autobahn.asyncio.websocket.WebSocketClientFactory and set ourMyClientProtocol on the factory (the highlighted lines)

4.3. Creating Clients 27

Page 36: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

3. Start a client using the factory, connecting to localhost 127.0.0.1 on TCP port 9000

Note: As can be seen, the boilerplate to create and run a client differ from Twisted, but the core code of creating afactory and setting our protocol (the highlighted lines) is identical (other than the differing import for the WebSocketfactory).

You can find complete code for above examples here:

• WebSocket Echo (Twisted-based)

• WebSocket Echo (Asyncio-based)

4.4 WebSocket Options

You can pass various options on both client and server side WebSockets; these are accomplished bycalling autobahn.websocket.WebSocketServerFactory.setProtocolOptions() or autobahn.websocket.WebSocketClientFactory.setProtocolOptions() with keyword arguments for each op-tion.

4.4.1 Common Options (server and client)

• logOctets: if True, log every byte

• logFrames: if True, log information about each frame

• trackTimings: if True, enable debug timing code

• utf8validateIncoming: if True (default), validate all incoming UTF8

• applyMask: if True (default) apply mask to frames, when available

• maxFramePayloadSize: if 0 (default), unlimited-sized frames allowed

• maxMessagePayloadSize: if 0 (default), unlimited re-assembled payloads

• autoFragmentSize: if 0 (default), don’t fragment

• failByDrop: if True (default), failed connections are terminated immediately

• echoCloseCodeReason: if True, echo back the close reason/code

• openHandshakeTimeout: timeout in seconds after which opening handshake will be failed (default: no timeout)

• closeHandshakeTimeout: timeout in seconds after which close handshake will be failed (default: no timeout)

• tcpNoDelay: if True (default), set NODELAY (Nagle) socket option

• autoPingInterval: if set, seconds between auto-pings

• autoPingTimeout: if set, seconds until a ping is considered timed-out

• autoPingSize: bytes of random data to send in ping messages (between 4 [default] and 125)

4.4.2 Server-Only Options

• versions: what versions to claim support for (default 8, 13)

• webStatus: if True (default), show a web page if visiting this endpoint without an Upgrade header

28 Chapter 4. WebSocket Programming

Page 37: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• requireMaskedClientFrames: if True (default), client-to-server frames must be masked

• maskServerFrames: if True, server-to-client frames must be masked

• perMessageCompressionAccept: if provided, a single-argument callable

• serveFlashSocketPolicy: if True, server a flash policy file (default: False)

• flashSocketPolicy: the actual flash policy to serve (default one allows everything)

• allowedOrigins: a list of origins to allow, with embedded *’s for wildcards; these are turned into regular ex-pressions (e.g. https://*.example.com:443 becomes ^https://.*.example.com:443$). When doing the matching,the origin is always of the form scheme://host:port with an explicit port. By default, we match with * (that is,anything). To match all subdomains of example.com on any scheme and port, you’d need *://*.example.com:*

• maxConnections: total concurrent connections allowed (default 0, unlimited)

• trustXForwardedFor: number of trusted web servers (reverse proxies) in front of this server which set the X-Forwarded-For header

4.4.3 Client-Only Options

• version: which version we are (default: 18)

• acceptMaskedServerFrames: if True, accept masked server-to-client frames (default False)

• maskClientFrames: if True (default), mask client-to-server frames

• serverConnectionDropTimeout: how long (in seconds) to wait for server to drop the connection when closing(default 1)

• perMessageCompressionOffers:

• perMessageCompressionAccept:

4.5 Upgrading

4.5.1 From < 0.7.0

Starting with release 0.7.0, Autobahn now supports both Twisted and asyncio as the underlying network library. Thisrequired renaming some modules.

Hence, code for Autobahn < 0.7.0

from autobahn.websocket import WebSocketServerProtocol

should be modified for Autobahn >= 0.7.0 for (using Twisted)

from autobahn.twisted.websocket import WebSocketServerProtocol

or (using asyncio)

from autobahn.asyncio.websocket import WebSocketServerProtocol

Two more small changes:

1. The method WebSocketProtocol.sendMessage had parameter binary renamed to isBinary (forconsistency with onMessage)

4.5. Upgrading 29

Page 38: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

2. The ConnectionRequest object no longer provides peerstr, but only peer, and the latter is a plain,descriptive string (this was needed since we now support both Twisted and asyncio, and also non-TCP transports)

30 Chapter 4. WebSocket Programming

Page 39: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 5

WAMP Programming

This guide gives an introduction to programming with WAMP in Python using Autobahn. (Go straight to WAMPExamples)

WAMP provides two communication patterns for application components to talk to each other

• Remote Procedure Calls

• Publish & Subscribe

and we will cover all four interactions involved in above patterns

1. Registering Procedures for remote calling

2. Calling Procedures remotely

3. Subscribing to Topics for receiving events

4. Publishing Events to topics

Note that WAMP is a “routed” protocol, and defines a Dealer and Broker role. Practically speaking, this means thatany WAMP client needs a WAMP Router to talk to. We provide an open-source one called Crossbar (there are otherrouters available). See also the WAMP specification for more details

Tip: If you are new to WAMP or want to learn more about the design principles behind WAMP, we have a longer texthere.

5.1 Application Components

WAMP is all about creating systems from loosely coupled application components. These application components arewhere your application-specific code runs.

A WAMP-based system consists of potentially many application components, which all connect to a WAMP router.The router is generic, which means, it does not run any application code, but only provides routing of events and calls.

31

Page 40: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

These components use either Remote Procedure Calls (RPC) or Publish/Subscribe (PubSub) to communicate. Eachcomponent can do any mix of: register, call, subscribe or publish.

For RPC, an application component registers a callable method at a URI (“endpoint”), and other components call itvia that endpoint.

In the Publish/Subscribe model, interested components subscribe to an event URI and when a publish to that URIhappens, the event payload is routed to all subscribers:

Hence, to create a WAMP application, you:

1. write application components

2. connect the components to a router

Note that each component can do any mix of registering, calling, subscribing and publishing – it is entirely up to youto logically group functionality as suits your problem space.

5.1.1 Creating Components

There are two ways to create components using Autobahn. One is based on deriving from a particular class andoverriding methods and the other is based on functions and decorators. The latter is the recommended approach (butnote that many examples and existing code use the subclassing approach). Both are fine and end up calling the samecode under the hood.

For both approaches you get to decide if you prefer to use Twisted or asyncio and express this through import. Thisis autobahn.twisted.* versus autobahn.asyncio.*

When using Twisted you import from autobahn.twisted.component:

from autobahn.twisted.component import Component

comp = Component(...)

@comp.on_joindef joined(session, details):

print("session ready")

whereas when you are using asyncio:

from autobahn.asyncio.component import Component

comp = Component(...)

@comp.on_joindef joined(session, details):

print("session ready")

As can be seen, the only difference between Twisted and asyncio is the import (line 1). The rest of the code is identical.For Twisted, you can use @inlineCallbacks or return Deferred from methods decorated with on_join; inPython 3 (with asyncio or Twisted) you would use coroutines (async def).

There are four “life cycle” events that Autobahn will trigger on your components: connect, join, leave,and disconnect. These all have corresponding decorators (or you can use code like comp.on('join',the_callback) if you prefer). We go over these events later.

32 Chapter 5. WAMP Programming

Page 41: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

5.1.2 Running Components

To actually make use of an application components, the component needs to connect to a WAMP router. Autobahnincludes a run() function that does the heavy lifting for you.

from autobahn.twisted.component import Componentfrom autobahn.twisted.component import run

comp = Component(transports=u"ws://localhost:8080/ws",realm=u"realm1",

)

@comp.on_joindef joined(session, details):

print("session ready")

if __name__ == "__main__":run([comp])

and with asyncio:

from autobahn.asyncio.component import Componentfrom autobahn.asyncio.component import run

comp = Component(transports=u"ws://localhost:8080/ws",realm=u"realm1",

)

@comp.on_joinasync def joined(session, details):

print("session ready")

if __name__ == "__main__":run([comp])

As can be seen, the only difference between Twisted and asyncio is the import (line 1 and 2). The rest of the code isidentical.

The configuration of the component is specified when you construct it; the above is the bare minimum – you canspecify many transports (which will be tried and re-tried in order) as well as authentication options, the realm to join,re-connection parameters, etcetera. See Component Configuration Options for details. A single Python program canrun many different Component instances at once and you can interconnect these as you see fit – so a single programcan have multiple WAMP connections (e.g. to different Realms or different WAMP routers) at once.

Tip: A Realm is a routing namespace and an administrative domain for WAMP. For example, a single WAMP routercan manage multiple Realms, and those realms are completely separate: an event published to topic T on a Realm R1is NOT received by a subscribe to T on Realm R2.

5.1.3 Running Subclass-Style Components

You can use the same “component” APIs to run a component based on subclassing ApplicationSession. In older codeit’s common to see autobahn.twisted.wamp.ApplicationRunner or autobahn.asyncio.wamp.ApplicationRunner. This runner lacks many of the options of the autobahn.twisted.component.

5.1. Application Components 33

Page 42: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

run() or autobahn.asyncio.component.run() functions, so although it can still be useful you likely wantto upgrade to run().

All you need to do is set the session_factory of a autobahn.twisted.component.Component instance toyour autobahn.twisted.wamp.ApplicationSession subclass (or pass it as a kwarg when creating theComponent)

comp = Component(session_factory=MyApplicationSession,

)

5.1.4 Patterns for More Complicated Applications

Many of the examples in this documentation use a decorator style with fixed, static WAMP URIs for registrations andsubscriptions. If you have a more complex application, you might want to create URIs at run-time or link severalComponent instances together.

It is important to remember that Component handles re-connection – this implies there are times when your com-ponent is not connected. The on_join handlers are run whenever a fresh WAMP session is started, so this is theappropriate way to hook in “initialization”-style code (on_leave is where “un-initialization” code goes). Note thateach new WAMP session will use a new instance of ApplicationSession.

Here’s a slightly more complex example that is a small Klein Web application that publishes to a WAMP session whena certian URL is requested (note that the Crossbario.io router supports various REST-style integrations already). Usinga similar pattern, you could tie together two or more Component instances (even connecting to two or more differentWAMP routers).

from autobahn.twisted.component import Componentfrom twisted.internet.defer import inlineCallbacks, Deferredfrom twisted.internet.endpoints import TCP4ServerEndpointfrom twisted.web.server import Sitefrom twisted.internet.task import react

# pip install kleinfrom klein import Klein

class WebApplication(object):"""A simple Web application that publishes an event every time theurl "/" is visited."""def __init__(self, app, wamp_comp):

self._app = appself._wamp = wamp_compself._session = None # "None" while we're disconnected from WAMP router

# associate ourselves with WAMP session lifecycleself._wamp.on('join', self._initialize)self._wamp.on('leave', self._uninitialize)# hook up Klein routesself._app.route(u"/", branch=True)(self._render_slash)

def _initialize(self, session, details):print("Connected to WAMP router")

(continues on next page)

34 Chapter 5. WAMP Programming

Page 43: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

self._session = session

def _uninitialize(self, session, reason):print(session, reason)print("Lost WAMP connection")self._session = None

def _render_slash(self, request):if self._session is None:

request.setResponseCode(500)return b"No WAMP session\n"

self._session.publish(u"com.myapp.request_served")return b"Published to 'com.myapp.request_served'\n"

@inlineCallbacksdef main(reactor):

component = Component(transports=u"ws://localhost:8080/ws",realm=u"crossbardemo",

)app = Klein()webapp = WebApplication(app, component)

# have our Web site listen on 8090site = Site(app.resource())server_ep = TCP4ServerEndpoint(reactor, 8090)port = yield server_ep.listen(site)print("Web application on {}".format(port))

# we don't *have* to hand over control of the reactor to# component.run -- if we don't want to, we call .start()# The Deferred it returns fires when the component is "completed"# (or errbacks on any problems).comp_d = component.start(reactor)

# When not using run() we also must start logging ourselves.import txaiotxaio.start_logging(level='info')

# If the Component raises an exception we want to exit. Note that# things like failing to connect will be swallowed by the# re-connection mechanisms already so won't reach here.

def _failed(f):print("Component failed: {}".format(f))done.errback(f)

comp_d.addErrback(_failed)

# wait forever (unless the Component raises an error)done = Deferred()yield done

if __name__ == '__main__':react(main)

5.1. Application Components 35

Page 44: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

5.1.5 Longer Example

Here is a more-complete example showing some of the options you can pass when setting up a Component. Thisexample can be run against the Crossbar.io router configuration that comes with Autobahn – just run crossbar start inexamples/router/ in your clone.

Twisted:

from autobahn.twisted.component import Component, runfrom autobahn.twisted.util import sleepfrom autobahn.wamp.types import RegisterOptionsfrom twisted.internet.defer import inlineCallbacks, returnValue

# to see how this works on the Crossbar.io side, see the example# router configuration in:# https://github.com/crossbario/autobahn-python/blob/master/examples/router/.crossbar/→˓config.json

component = Component(# you can configure multiple transports; here we use two different# transports which both exist in the demo routertransports=[

{u"type": u"websocket",u"url": u"ws://localhost:8080/auth_ws",u"endpoint": {

u"type": u"tcp",u"host": u"localhost",u"port": 8080,

},# you can set various websocket options here if you wantu"options": {

u"open_handshake_timeout": 100,}

},],# authentication can also be configured (this will only work on# the demo router on the first transport above)authentication={

u"cryptosign": {u'authid': u'alice',# this key should be loaded from disk, database etc never burned into

→˓code like this...u'privkey':

→˓'6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c',}

},# must provide a realmrealm=u"crossbardemo",

)

@component.on_join@inlineCallbacksdef join(session, details):

print("joined {}: {}".format(session, details))yield sleep(1)print("Calling 'com.example'")

(continues on next page)

36 Chapter 5. WAMP Programming

Page 45: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

res = yield session.call(u"example.foo", 42, something="nothing")print("Result: {}".format(res))yield session.leave()

@component.register(u"example.foo",options=RegisterOptions(details_arg='details'),

)@inlineCallbacksdef foo(*args, **kw):

print("foo called: {}, {}".format(args, kw))for x in range(5, 0, -1):

print(" returning in {}".format(x))yield sleep(1)

print("returning '42'")returnValue(42)

if __name__ == "__main__":run([component])

The Python3 / asyncio version of the same example is nearly identical except for some imports (and the use of asyncdef instead of Twisted’s decorators):

asyncio:

from autobahn.asyncio.component import Component, runfrom asyncio import sleepfrom autobahn.wamp.types import RegisterOptions

# to see how this works on the Crossbar.io side, see the example# router configuration in:# https://github.com/crossbario/autobahn-python/blob/master/examples/router/.crossbar/→˓config.json

component = Component(# you can configure multiple transports; here we use two different# transports which both exist in the demo routertransports=[

{u"type": u"websocket",u"url": u"ws://localhost:8080/auth_ws",u"endpoint": {

u"type": u"tcp",u"host": u"localhost",u"port": 8080,

},# you can set various websocket options here if you wantu"options": {

u"open_handshake_timeout": 100,}

},],# authentication can also be configured (this will only work on# the demo router on the first transport above)authentication={

(continues on next page)

5.1. Application Components 37

Page 46: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

u"cryptosign": {u'authid': u'alice',# this key should be loaded from disk, database etc never burned into

→˓code like this...u'privkey':

→˓'6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c',}

},# must provide a realmrealm=u"crossbardemo",

)

@component.on_joinasync def join(session, details):

print("joined {}: {}".format(session, details))await sleep(1)print("Calling 'com.example'")res = await session.call(u"example.foo", 42, something="nothing")print("Result: {}".format(res))await session.leave()

@component.register(u"example.foo",options=RegisterOptions(details_arg='details'),

)async def foo(*args, **kw):

print("foo called: {}, {}".format(args, kw))for x in range(5, 0, -1):

print(" returning in {}".format(x))await sleep(1)

print("returning '42'")return 42

if __name__ == "__main__":run([component])

5.2 Component Configuration Options

Most of the arguments given when creating a new Component are a series of dict instances containing“configuration”-style information. These are documented in autobahn.wamp.component.Component so wego through the most important ones here:

5.2.1 transports=

You may define any number of transports; these are tried in round-robin order when doing connections (and subsequentre-connections). If the is_fatal= predicate is used and returns True for any errors, that transport won’t be usedany more (and when no transports remain, the Component has “failed”).

Each transport is defined similarly to “connecting transports” in Crossbar.io but as a simplification a plain uni-code URI may be used, for example transports=u"ws://example.com/ws" or transports=[u"ws:/

38 Chapter 5. WAMP Programming

Page 47: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

/example.com/ws"]. If using a dict instead of a string you can specify the following keys:

• type: "websocket" (default) or "rawsocket"

• url: the URL of the router to connect to (very often, this will be the same as the “endpoint” host but not always)

• endpoint: (optional; can be inferred from above) - type: "tcp" or "unix" - host, port: onlyfor type="tcp" - path: only for type="unix" - tls: bool (advanced Twisted users can passCertificateOptions); this is also inferred from a wss: scheme.

In addition, each transport may have some options related to re-connections:

• max_retries: (default -1, “try forever”) or a hard limit.

• max_retry_delay: (default 300)

• initial_retry_delay: (default 1.5) how long we wait to re-connect the first time

• retry_delay_growth: (default 1.5) a multiplier expanding our delay each try (so the second re-connectwe wait retry_delay_growth * initial_retry_delay seconds).

• retry_delay_jitter: (default 0.1) percent of total retry delay to add/subtract as jitter

After a successful connection, all re-connection values are set back to their original values.

5.2.2 realm=

Each WAMP Session is associated with precisely one realm, and so is each Component. A “realm” is a logicallyseparated WAMP URI space (and is isolated from all other realms that may exist on a WAMP router). You must passa unicode string here.

5.2.3 session_factory=

Leaving this as None should be fine for most users. You may pass an ApplicationSession subclass here (or evena callable that takes a single config argument and returns an instance implementing IApplicationSession)to create new session objects. This can be used by users of the “subclass”-style API who still want to take advantageof the configuration of Component and run(). The session argument passed in many of the callbacks will be aninstance of this (see also Session Lifecycle).

5.2.4 authentication=

This contains a dict mapping an authenticator name to its configuration. You do not have to have any authenticationinformation, in which case anonymous will be used. Currently valid authenticators are: anonymous, ticket,wampcra, cryptosign (experimental) and scram (experimental).

Typically the administrator of your WAMP router will decide which authentication methods are allowed. See forexample Crossbar.io’s authentication documentation for some discussion of the various methods.

anonymous accepts no options. Most methods accept options for:

• authextra: application-specific information

• authid: unicode username

• authrole: the desired role inside the realm

The other authentication methods take additional options as indicated below:

• wampcra: also accepts secret (the password)

5.2. Component Configuration Options 39

Page 48: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• cryptosign (experimental): also accepts privkey, the hex-encoded ed25519 private key

• scram (experimental): also requires nonce (hex-encoded), kdf ("argon2id-13" or "pbkdf2"), salt(hex-encoded), iterations (integer) and optionally memory (integer) and channel_binding (currentlyignored).

• ticket: accepts only the ticket option

5.3 Running a WAMP Router

The component we’ve created attempts to connect to a WAMP router running locally which accepts connections onport 8080, and for a realm crossbardemo.

Our suggested way is to use Crossbar.io as your WAMP router. There are other WAMP routers besides Crossbar.io aswell.

Once you’ve installed Crossbar.io, run the example configuration from examples/router in your Autobahn clone.If you want to start fresh, you can instead do this:

crossbar init

This will create the default Crossbar.io node configuration ./.crossbar/config.json. You can then startCrossbar.io by doing:

crossbar start

Note: The defaults in the above will not work with the examples in the repository nor this documentation; please usethe example router configuration that ships with Autobahn (in examples/router/.crossbar/).

5.4 Remote Procedure Calls

Remote Procedure Call (RPC) is a messaging pattern involving peers of three roles:

• Caller

• Callee

• Dealer

A Caller issues calls to remote procedures by providing the procedure URI and any arguments for the call. The Calleewill execute the procedure using the supplied arguments to the call and return the result of the call to the Caller.

Callees register procedures they provide with Dealers. Callers initiate procedure calls first to Dealers. Dealers routecalls incoming from Callers to Callees implementing the procedure called, and route call results back from Callees toCallers.

The Caller and Callee will usually run application code, while the Dealer works as a generic router for remoteprocedure calls decoupling Callers and Callees. Thus, the Caller can be in a separate process (even a separate imple-mentation language) from the Callee.

5.4.1 Registering Procedures

To make a procedure available for remote calling, the procedure needs to be registered. Registering a procedure isdone by calling ICallee.register from a session.

40 Chapter 5. WAMP Programming

Page 49: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Here is an example using Twisted; note that we’ve eliminated the configuration of the Component for clarity; seeabove for full example.

1 from autobahn.twisted.component import Component, run2

3 component = Component(...)4

5 @component.on_join6 @inlineCallbacks7 def joined(session, details):8 print("session ready")9

10 def add2(x, y):11 return x + y12

13 try:14 yield session.register(add2, u'com.myapp.add2')15 print("procedure registered")16 except Exception as e:17 print("could not register procedure: {0}".format(e))

The procedure add2 is registered (line 14) under the URI u"com.myapp.add2" immediately in the on_joincallback which fires when the session has connected to a Router and joined a Realm. Another way to arrange forprocedures to be registered is with the @register decorator:

1 from autobahn.twisted.component import Component, run2

3 component = Component(...)4

5 @component.register6 def add2(x, y):7 return x + y

Tip: You can register local functions like in above example, global functions as well as methods on class instances.Further, procedures can also be automatically registered using decorators.

When the registration succeeds, authorized callers will immediately be able to call the procedure (see Calling Proce-dures) using the URI under which it was registered (u"com.myapp.add2").

A registration may also fail, e.g. when a procedure is already registered under the given URI or when the session isnot authorized to register procedures.

Using asyncio, the example looks identical except for the imports (note that add could be async def here if itneeded to do other work).

1 from autobahn.asyncio.component import Component, run2

3 component = Component(...)4

5 @component.register6 def add2(x, y):7 return x + y

The differences compared with the Twisted variant are:

• the import of ApplicationSession

• the use of async keyword to declare co-routines

5.4. Remote Procedure Calls 41

Page 50: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• the use of await instead of yield

5.4.2 Calling Procedures

Calling a procedure (that has been previously registered) is done using autobahn.wamp.interfaces.ICaller.call().

Here is how you would call the procedure add2 that we registered in Registering Procedures under URI com.myapp.add2 in Twisted

1 from autobahn.twisted.component import Component, run2 from twisted.internet.defer import inlineCallbacks3

4

5 component = Component(...)6

7 @component.on_join8 @inlineCallbacks9 def joined(session, details):

10 print("session ready")11 try:12 res = yield session.call(u'com.myapp.add2', 2, 3)13 print("call result: {}".format(res))14 except Exception as e:15 print("call error: {0}".format(e))

And here is the same done on asyncio

1 from autobahn.asyncio.component import Component, run2

3

4 component = Component(...)5

6 @component.on_join7 async def joined(session, details):8 print("session ready")9 try:

10 res = await session.call(u'com.myapp.add2', 2, 3)11 print("call result: {}".format(res))12 except Exception as e:13 print("call error: {0}".format(e))

5.5 Publish & Subscribe

Publish & Subscribe (PubSub) is a messaging pattern involving peers of three roles:

• Publisher

• Subscriber

• Broker

A Publisher publishes events to topics by providing the topic URI and any payload for the event. Subscribers of thetopic will receive the event together with the event payload.

Subscribers subscribe to topics they are interested in with Brokers. Publishers initiate publication first at a Broker.Brokers route events incoming from Publishers to Subscribers that are subscribed to respective topics.

42 Chapter 5. WAMP Programming

Page 51: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

The Publisher and Subscriber will usually run application code, while the Broker works as a generic router for eventsthus decoupling Publishers from Subscribers. That is, there can be many Subscribers written in different languageson different machines which can all receive a single event published by an independant Publisher.

5.5.1 Subscribing to Topics

To receive events published to a topic, a session needs to first subscribe to the topic. Subscribing to a topic is done bycalling autobahn.wamp.interfaces.ISubscriber.subscribe().

Here is a Twisted example:

1 from autobahn.twisted.component import Component2 from twisted.internet.defer import inlineCallbacks3

4

5 component = Component(...)6

7 @component.on_join8 @inlineCallbacks9 def joined(session, details):

10 print("session ready")11

12 def oncounter(count):13 print("event received: {0}", count)14

15 try:16 yield session.subscribe(oncounter, u'com.myapp.oncounter')17 print("subscribed to topic")18 except Exception as e:19 print("could not subscribe to topic: {0}".format(e))

We create an event handler function oncounter (you can name that as you like) which will get called whenever anevent for the topic is received.

To subscribe (line 15), we provide the event handler function (oncounter) and the URI of the topic to which wewant to subscribe (u'com.myapp.oncounter').

When the subscription succeeds, we will receive any events published to u'com.myapp.oncounter'. Note thatwe won’t receive events published before the subscription succeeds.

The corresponding asyncio code looks like this

1 from autobahn.twisted.component import Component2

3

4 component = Component(...)5

6 @component.on_join7 async def joined(session, details):8 print("session ready")9

10 def oncounter(count):11 print("event received: {0}", count)12

13 try:14 yield session.subscribe(oncounter, u'com.myapp.oncounter')15 print("subscribed to topic")

(continues on next page)

5.5. Publish & Subscribe 43

Page 52: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

16 except Exception as e:17 print("could not subscribe to topic: {0}".format(e))

Again, nearly identical to Twisted. Note that when using the Component APIs we can use a shortcut to the above(e.g. perhaps there’s nothing else to do in on_join). This shortcut works similarly for Twisted, so we only show anasyncio example:

1 from autobahn.twisted.component import Component2

3

4 component = Component(...)5

6 @component.subscribe(u"com.myapp.oncounter")7 def oncounter(count):8 print("event received: {0}", count)

5.5.2 Publishing Events

Publishing an event to a topic is done by calling autobahn.wamp.interfaces.IPublisher.publish().

Events can carry arbitrary positional and keyword based payload – as long as the payload is serializable in JSON.

Here is a Twisted example that will publish an event to topic u'com.myapp.oncounter' with a single (posi-tional) payload being a counter that is incremented for each publish:

1 from autobahn.twisted.component import Component2 from autobahn.twisted.util import sleep3 from twisted.internet.defer import inlineCallbacks4

5

6 component = Component(...)7

8

9 @component.on_join10 @inlineCallbacks11 def joined(session, details):12 print("session ready")13

14 counter = 015 while True:16 # publish() only returns a Deferred if we asked for an acknowledgement17 session.publish(u'com.myapp.oncounter', counter)18 counter += 119 yield sleep(1)

The corresponding asyncio code looks like this

1 from autobahn.asyncio.component import Component2 from asyncio import sleep3

4

5 component = Component(...)6

7

8 @component.on_join(continues on next page)

44 Chapter 5. WAMP Programming

Page 53: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

9 async def joined(session, details):10 print("session ready")11

12 counter = 013 while True:14 # publish() is only async if we asked for an acknowledgement15 session.publish(u'com.myapp.oncounter', counter)16 counter += 117 await sleep(1)

When publishing, you can pass an options= kwarg which is an instance of PublishOptions. Many of the optionsrequire support from the router.

• whitelisting and blacklisting (all the eligible* and exclude* options) can affect which subscribers receive thepublish; see crossbar documentation for more information;

• retain= asks the router to retain the message;

• acknowledge= asks the router to notify you it received the publish (note that this does not wait for every sub-scriber to have received the publish) and causes publish() to return a Future/Deferred.

Tip: By default, a publisher will not receive an event it publishes even when the publisher is itself subscribed to thetopic subscribed to. This behavior can be overridden; see PublishOptions and exclude_me=False.

Tip: By default, publications are unacknowledged. This means, a publish() may fail silently (like when thesession is not authorized to publish to the given topic). This behavior can be overridden; see PublishOptions andacknowledge=True.

5.6 Session Lifecycle

A WAMP application component has this lifecycle:

1. component created

2. transport connected (ISession.onConnect called)

3. authentication challenge received (only for authenticated WAMP sessions, ISession.onChallenge called)

4. session established (realm joined, ISession.onJoin called)

5. session closed (realm left, ISession.onLeave called)

6. transport disconnected (ISession.onDisconnect called)

In the Component API, there are similar corresponding events. The biggest difference is the lack of “challenge”events (you pass authentication configuration instead) and the addition of a “ready” event. You can subscribe to theseevents directly using a “listener” style API or via decorators. The events are:

1. “connect”: transport connected

2. “join”: session has successfully joined a realm

3. “ready”: indicates that the realm has been joined and all “join” handlers have completed (including async ones)

4. “leave”: session has left a realm

5.6. Session Lifecycle 45

Page 54: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

5. “disconnect”: transport has disconnected

You can use the method autobahn.wamp.component.Component.on() to subscribe directly to events witha listener-function. For example, component.on('ready', my_ready_listener). Note that on a singleComponent instance these callbacks can happen multiple times (e.g. if the component is disconnected and thenreconnects, its connect message will fire again after the disconnect). However, they will always be in order (i.e.you can’t join until after a connect and ready always comes after join).

There is also still the older “subclassing” based API, which is still supported and can be used if you prefer. This APIinvolves subclassing ApplicationSession and overriding methods corresponding to the events (see ISessionfor more information):

class CustomSession(ApplicationSession):def __init__(self, config=None):

ApplicationSession.__init__(self, config)print("component created")

def onConnect(self):print("transport connected")self.join(self.config.realm)

def onChallenge(self, challenge):print("authentication challenge received")

def onJoin(self, details):print("session joined")

def onLeave(self, details):print("session left")

def onDisconnect(self):print("transport disconnected")

5.7 Logging

Internally, Autobahn uses txaio as an abstraction layer over Twisted and asyncio APIs. txaio also provides an ab-stracted logging API, which is what both Autobahn and Crossbar use.

There is a txaio Programming Guide which includes information on logging. If you are writing new code, you canchoose the txaio APIs for maximum compatibility and runtime-efficiency (see below). If you prefer to write idiomaticlogging code to “go with” the event-based frameword you’ve chosen, that’s possible as well. For asyncio this isPython’s built-in logging module; for Twisted it is the post-15.2.0 logging API. The logging system in txaio is able tointeroperate with the legacy Twisted logging API as well.

The txaio API encourages a more structured approach while still achieving easily-rendered text logging mes-sages. The basic idiom is to use new-style Python formatting strings and pass any “data” as kwargs. So a typi-cal logging call might look like: self.log.info("Knob {frob.name} moved {degrees} right.",knob=an_obj, degrees=42) and if the “info” log level is not enabled, the string won’t be “interpolated” (i.e.str() will not be invoked on any of the args, and a new string won’t be produced). On top of that, logging ob-servers may examine the kwargs and do things beyond “normal” logging. This is very much inspired by twisted.logger; you can read the Twisted logging documentation for more insight.

Before any logging happens of course you must activate the logging system. There is a convenience method intxaio called txaio.start_logging. This will use twisted.logger.globalLogBeginner on Twistedor logging.Logger.addHandler under asyncio and allows you to specify and output stream and/or a log

46 Chapter 5. WAMP Programming

Page 55: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

level. Valid levels are the list of strings in txaio.interfaces.log_levels. If you’re using the high-level autobahn.twisted.component.run() or autobahn.asyncio.component.run() APIs, log-ging will be started for you.

If you have instead got your own log-starting code (e.g. twistd) or Twisted/asyncio specific log handlers(logging.Handler subclass on asyncio and ILogObserver implementer under Twisted) then you will stillget Autobahn and Crossbar messages. Probably the formatting will be slightly different from what txaio.start_logging provides. In either case, do not depend on the formatting of the messages e.g. by “screen-scraping” the logs.

We very much recommend using the ‘‘txaio.start_logging()‘‘ method of activating the logging system, as we’vegone to pains to ensure that over-level logs are a “no-op” and incur minimal runtime cost. We achieve this by re-binding all out-of-scope methods on any logger created by txaio.make_logger() to a do-nothing function (bysaving weak-refs of all the loggers created); at least on PyPy this is very well optimized out. This allows us to begenerous with .debug() or .trace() calls without incurring very much overhead. Your Milage May Vary usingother methods. If you haven’t called txaio.start_logging() this optimization is not activated.

5.8 Upgrading

5.8.1 From < 0.8.0

Starting with release 0.8.0, Autobahn now supports WAMP v2, and also support both Twisted and asyncio. Thisrequired changing module naming for WAMP v1 (which is Twisted only).

Hence, WAMP v1 code for Autobahn < 0.8.0

from autobahn.wamp import WampServerFactory

should be modified for Autobahn >= 0.8.0 for (using Twisted)

from autobahn.wamp1.protocol import WampServerFactory

Warning: WAMP v1 will be deprecated with the 0.9 release of Autobahn which is expected in Q4 2014.

5.8.2 From < 0.9.4

Starting with release 0.9.4, all WAMP router code in Autobahn has been split out and moved to Crossbar.io. Pleasesee the announcement here.

5.8. Upgrading 47

Page 56: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

48 Chapter 5. WAMP Programming

Page 57: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 6

XBR Programming

Autobahn comes with built-in support for XBR. This chapter contains documentation of writing XBR buyers andsellers in Python using Autobahn.

• On-chain XBR smart contracts

– SimpleBlockchain

– SimpleBlockchain Example

– Using the ABI files

– Data stored on-chain

• Off-chain XBR market maker

– SimpleBuyer

– SimpleBuyer Example

– SimpleSeller

– SimpleSeller Example

– KeySeries

• Interface Reference

– IMarketMaker

– IProvider

– IConsumer

– ISeller

– IBuyer

49

Page 58: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

6.1 On-chain XBR smart contracts

The root anchor of the XBR network is a set of smart contracts on the Ethereum blockchain. The contracts are writtenin Solidity and published as open-source on GitHub.

To talk to the XBR smart contracts on the blockchain, you need two things:

1. the XBR smart contract addresses and

2. the XBR smart contract ABI files (JSON)

Both of which are built into the Autobahn library.

6.1.1 SimpleBlockchain

While you can use just the raw addresses and ABI blobs contained in Autobahn, and use whatever way and form totalk directly to the blockchain fully on your own, Autobahn also provides a convenient blockchain client with specificfunctions directly supporting XBR:

6.1.2 SimpleBlockchain Example

Here is a complete example blockchain client:

import argparsefrom binascii import a2b_hex, b2a_hexfrom autobahn import xbrfrom twisted.internet.task import reactfrom twisted.internet.defer import inlineCallbacks

@inlineCallbacksdef main(reactor, gateway, adr):

sbc = xbr.SimpleBlockchain(gateway)yield sbc.start()

print('status for address 0x{}:'.format(b2a_hex(adr).decode()))

# get ETH and XBR account balances for addressbalances = yield sbc.get_balances(adr)print('balances: {}'.format(balances))

# get XBR network membership status for addressmember_status = yield sbc.get_member_status(adr)print('member status: {}'.format(member_status))

if __name__ == '__main__':parser = argparse.ArgumentParser()

parser.add_argument('--gateway',dest='gateway',type=str,default=None,help='Ethereum HTTP gateway URL or None for auto-select.')

parser.add_argument('--adr',

(continues on next page)

50 Chapter 6. XBR Programming

Page 59: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

dest='adr',type=str,default=None,help='Ethereum address to lookup.')

args = parser.parse_args()

react(main, (args.gateway, a2b_hex(args.adr[2:],)))

Here is example output of above program with two different addresses, only one being a member, and with differentbalances of ETH and XBR.

connected to network 5777 at provider "http://localhost:1545"status for address 0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1:balances: {'ETH': 9999866871000000000000, 'XBR': 1000000000000000000000000000}member status: None

connected to network 5777 at provider "http://localhost:1545"status for address 0xffcf8fdee72ac11b5c542428b35eef5769c409f0:balances: {'ETH': 9999999999999999625429, 'XBR': 0}member status: {'eula': 'QmU7Gizbre17x6V2VR1Q2GJEjz6m8S1bXmBtVxS2vmvb81', 'profile':→˓None}

6.1.3 Using the ABI files

To directly use the embedded ABI files:

import jsonimport pkg_resourcesfrom pprint import pprint

with open(pkg_resources.resource_filename('xbr', 'contracts/XBRToken.json')) as f:data = json.loads(f.read())abi = data['abi']pprint(abi)

6.1.4 Data stored on-chain

See the XBRNetwork contract:

/// Current XBR Network members ("member directory").mapping(address => Member) private members;

/// Current XBR Domains ("domain directory")mapping(bytes16 => Domain) private domains;

/// Current XBR Nodes ("node directory");mapping(bytes16 => Node) private nodes;

/// Index: node public key => (market ID, node ID)mapping(bytes32 => bytes16) private nodesByKey;

/// Current XBR Markets ("market directory")

(continues on next page)

6.1. On-chain XBR smart contracts 51

Page 60: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

mapping(bytes16 => Market) private markets;

/// Index: maker address => market IDmapping(address => bytes16) private marketsByMaker;

6.2 Off-chain XBR market maker

6.2.1 SimpleBuyer

Autobahn includes a “simple buyer” for use in buyer delegate user services which is able to automatically quote andbuy data encryption keys via the market maker from sellers in a market.

The simple buyer operates in the background and automatically buys keys on demand, as the user calls “un-wrap(ciphertext)” on received XBR encrypted application payload:

6.2.2 SimpleBuyer Example

Here is a complete example buyer:

import binasciiimport os

from autobahn.twisted.component import Component, runfrom autobahn.xbr import SimpleBuyerfrom autobahn.wamp.types import SubscribeOptions

comp = Component(transports=os.environ.get('XBR_INSTANCE', 'wss://continental2.crossbario.com/ws'),realm=os.environ.get('XBR_REALM', 'realm1'),extra={

'market_maker_adr': os.environ.get('XBR_MARKET_MAKER_ADR','0xff035c911accf7c7154c51cb62460b50f43ea54f'),

'buyer_privkey': os.environ.get('XBR_BUYER_PRIVKEY','646f1ce2fdad0e6deeeb5c7e8e5543bdde65e86029e2fd9fc169899c440a7913'),

})

@comp.on_joinasync def joined(session, details):

print('Buyer session joined', details)

market_maker_adr = binascii.a2b_hex(session.config.extra['market_maker_adr'][2:])print('Using market maker adr:', session.config.extra['market_maker_adr'])

buyer_privkey = binascii.a2b_hex(session.config.extra['buyer_privkey'])

buyer = SimpleBuyer(market_maker_adr, buyer_privkey, 100)balance = await buyer.start(session, details.authid)print("Remaining balance={}".format(balance))

async def on_event(key_id, enc_ser, ciphertext, details=None):

(continues on next page)

52 Chapter 6. XBR Programming

Page 61: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

payload = await buyer.unwrap(key_id, enc_ser, ciphertext)print('Received event {}:'.format(details.publication), payload)

await session.subscribe(on_event, "io.crossbar.example",options=SubscribeOptions(details=True))

if __name__ == '__main__':run([comp])

6.2.3 SimpleSeller

Autobahn includes a “simple seller” for use in seller delegate user services which is able to automatically offer andsell data encryption keys via the market maker to buyers in a market:

6.2.4 SimpleSeller Example

Here is a complete example seller:

import binasciiimport osfrom time import sleepfrom uuid import UUID

from autobahn.twisted.component import Component, runfrom autobahn.twisted.util import sleepfrom autobahn.wamp.types import PublishOptionsfrom autobahn.xbr import SimpleSeller

comp = Component(transports=os.environ.get('XBR_INSTANCE', 'wss://continental2.crossbario.com/ws'),realm=os.environ.get('XBR_REALM', 'realm1'),extra={

'market_maker_adr': os.environ.get('XBR_MARKET_MAKER_ADR','0xff035c911accf7c7154c51cb62460b50f43ea54f'),

'seller_privkey': os.environ.get('XBR_SELLER_PRIVKEY','646f1ce2fdad0e6deeeb5c7e8e5543bdde65e86029e2fd9fc169899c440a7913'),

})

running = False

@comp.on_joinasync def joined(session, details):

print('Seller session joined', details)global runningrunning = True

market_maker_adr = binascii.a2b_hex(session.config.extra['market_maker_adr'][2:])print('Using market maker adr:', session.config.extra['market_maker_adr'])

seller_privkey = binascii.a2b_hex(session.config.extra['seller_privkey'])

(continues on next page)

6.2. Off-chain XBR market maker 53

Page 62: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

(continued from previous page)

api_id = UUID('627f1b5c-58c2-43b1-8422-a34f7d3f5a04').bytestopic = 'io.crossbar.example'counter = 1

seller = SimpleSeller(market_maker_adr, seller_privkey)seller.add(api_id, topic, 35, 10, None)await seller.start(session)

print('Seller has started')

while running:payload = {'data': 'py-seller', 'counter': counter}key_id, enc_ser, ciphertext = await seller.wrap(api_id,

topic,payload)

pub = await session.publish(topic, key_id, enc_ser, ciphertext,options=PublishOptions(acknowledge=True))

print('Published event {}: {}'.format(pub.id, payload))

counter += 1await sleep(1)

@comp.on_leavedef left(session, details):

print('Seller session left', details)global runningrunning = False

if __name__ == '__main__':run([comp])

6.2.5 KeySeries

Helper class used in SimpleSeller to create an auto-rotating (time-interval based) data encryption key series:

6.3 Interface Reference

6.3.1 IMarketMaker

6.3.2 IProvider

6.3.3 IConsumer

6.3.4 ISeller

6.3.5 IBuyer

54 Chapter 6. XBR Programming

Page 63: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 7

WebSocket Examples

7.1 Basic Examples

Note: The examples here demonstrate WebSocket programming with Autobahn and are available in Twisted andasyncio-based variants respectively.

7.1.1 Echo

Twisted / asyncio

A simple WebSocket echo server and client.

7.1.2 Slow Square

Twisted / asyncio

This example shows a WebSocket server that will receive a JSON encode float over WebSocket, slowly compute thesquare, and send back the result. The example is intended to demonstrate how to use co-routines inside WebSockethandlers.

7.1.3 Testee

Twisted / asyncio

The example implements a testee for testing against Autobahn|Testsuite.

55

Page 64: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

7.2 Additional Examples

Note: The examples here demonstrate various further features and aspects of WebSocket programming with Auto-bahn. However, these examples are currently only available for Twisted.

7.2.1 Secure WebSocket

Twisted

How to run WebSocket over TLS (“wss”).

7.2.2 WebSocket and Twisted Web

Twisted

How to run WebSocket under Twisted Web. This is a very powerful feature, as it allows you to create a completeHTTP(S) resource hierarchy with different services like static file serving, REST and WebSocket combined under oneserver.

7.2.3 Twisted Web, WebSocket and WSGI

Twisted

This example shows how to run Flask (or any other WSGI compliant Web thing) under Twisted Web and combine thatwith WebSocket.

7.2.4 Secure WebSocket and Twisted Web

Twisted

A variant of the previous example that runs a HTTPS server with secure WebSocket on a subpath.

7.2.5 WebSocket Ping-Pong

Twisted

The example demonstrates how to trigger and process WebSocket pings and pongs.

7.2.6 More

• WebSocket Authentication with Mozilla Persona

• Broadcasting over WebSocket

• WebSocket Compression

• WebSocket over Twisted Endpoints

• Using HTTP Headers with WebSocket

• WebSocket on Multicore

56 Chapter 7. WebSocket Examples

Page 66: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

58 Chapter 7. WebSocket Examples

Page 67: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 8

WAMP Examples

NOTE that for all examples you will need to run a router. We develop Crossbar.io and there are other routersavailable as well. We include a working Crossbar.io configuration in the examples/router/ subdirectory as well asinstructions on how to run it.

8.1 Overview of Examples

The examples are organized between asyncio and Twisted at the top-level, with similarly-named examples demon-strating the same functionality with the respective framework.

Each example typically includes four things:

• frontend.py: the Caller or Subscriber, in Python

• backend.py: the Callee or Publisher, in Python

• frontend.js: JavaScript version of the frontend

• backend.js: JavaScript version of the backend

• *.html: boilerplate so a browser can run the JavaScript

So for each example, you start one backend and one frontend component (your choice). You can usually start multiplefrontend components with no problem, but will get errors if you start two backends trying to register at the sameprocedure URI (for example).

Still, you are encouraged to try playing with mixing and matching the frontend and backend components, startingmultiple front-ends, etc. to explore Crossbar and Autobahn’s behavior. Often the different examples use similar URIsfor procedures and published events, so you can even try mixing between the examples.

The provided Crossbar.io configuration will run a Web server that you can visit at http://localhost:8080 and includeslinks to the frontend/backend HTML for the javascript versions. Usually these just use console.log() so you’llhave to open up the JavaScript console in your browser to see it working.

59

Page 68: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

8.2 Automatically Run All Examples

There is a script (./examples/run-all-examples.py) which runs all the WAMP examples for 5 secondseach, this asciicast shows you how (see comments for how to run it yourself):

8.3 Publish & Subscribe (PubSub)

• Basic Twisted - asyncio - Demonstrates basic publish and subscribe.

• Complex Twisted - asyncio - Demonstrates publish and subscribe with complex events.

• Options Twisted - asyncio - Using options with PubSub.

• Unsubscribe Twisted - asyncio - Cancel a subscription to a topic.

8.4 Remote Procedure Calls (RPC)

• Time Service Twisted - asyncio - A trivial time service - demonstrates basic remote procedure feature.

• Slow Square Twisted - asyncio - Demonstrates procedures which return promises and return asynchronously.

• Arguments Twisted - asyncio - Demonstrates all variants of call arguments.

• Complex Result Twisted - asyncio - Demonstrates complex call results (call results with more than one positionalor keyword results).

• Errors Twisted - asyncio - Demonstrates error raising and catching over remote procedures.

• Progressive Results Twisted - asyncio - Demonstrates calling remote procedures that produce progressive results.

• Options Twisted - asyncio - Using options with RPC.

8.5 I’m Confused, Just Tell Me What To Run

If all that is too many options to consider, you want to do this:

1. Open 3 terminals

2. In terminal 1, setup and run a local Crossbar in the root of your Autobahn checkout.

3. In terminals 2 and 3, go to the root of your Autobahn checkout and activate the virtualenv from step 2 (sourcevenv-autobahn/bin/activate)

4. In terminal 2 run python ./examples/twisted/wamp/rpc/arguments/backend.py

5. In terminal 3 run python ./examples/twisted/wamp/rpc/arguments/frontend.py

The above procedure is gone over in this this asciicast:

60 Chapter 8. WAMP Examples

Page 69: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 9

API Reference

The following is a API reference of Autobahn generated from Python source code and docstrings.

Warning: This is a complete reference of the public API of Autobahn. User code and applications should onlyrely on the public API, since internal APIs can (and will) change without any guarantees. Anything not listed hereis considered a private API.

9.1 Module autobahn.util

autobahn.util.public(obj)The public user API of Autobahn is marked using this decorator. Everything that is not decorated @public islibrary internal, can change at any time and should not be used in user program code.

autobahn.util.encode_truncate(text, limit, encoding=’utf8’, return_encoded=True)Given a string, return a truncated version of the string such that the UTF8 encoding of the string is smaller thanthe given limit.

This function correctly truncates even in the presence of Unicode code points that encode to multi-byte encod-ings which must not be truncated in the middle.

Parameters

• text (str) – The (Unicode) string to truncate.

• limit (int) – The number of bytes to limit the UTF8 encoding to.

• encoding (str) – Truncate the string in this encoding (default is utf-8).

• return_encoded (bool) – If True, return the string encoded into bytes according tothe specified encoding, else return the string as a string.

Returns The truncated string.

Return type str or bytes

61

Page 70: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

autobahn.util.xor(d1, d2)XOR two binary strings of arbitrary (equal) length.

Parameters

• d1 (binary) – The first binary string.

• d2 (binary) – The second binary string.

Returns XOR of the binary strings (XOR(d1, d2))

Return type bytes

autobahn.util.utcnow()Get current time in UTC as ISO 8601 string.

Returns Current time as string in ISO 8601 format.

Return type str

autobahn.util.utcstr(ts=None)Format UTC timestamp in ISO 8601 format.

Note: to parse an ISO 8601 formatted string, use the iso8601 module instead (e.g. iso8601.parse_date("2014-05-23T13:03:44.123Z")).

Parameters ts (instance of datetime.datetime or None) – The timestamp to format.

Returns Timestamp formatted in ISO 8601 format.

Return type str

autobahn.util.id()Generate a new random integer ID from range [0, 2**53].

The generated ID is based on a pseudo-random number generator (Mersenne Twister, which has a period of2**19937-1). It is NOT cryptographically strong, and hence NOT suitable to generate e.g. secret keys or accesstokens.

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double suchthat all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type(JavaScript, Lua, etc).

Returns A random integer ID.

Return type int

autobahn.util.rid()Generate a new random integer ID from range [0, 2**53].

The generated ID is uniformly distributed over the whole range, doesn’t have a period (no pseudo-randomgenerator is used) and cryptographically strong.

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double suchthat all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type(JavaScript, Lua, etc).

Returns A random integer ID.

Return type int

62 Chapter 9. API Reference

Page 71: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

autobahn.util.newid(length=16)Generate a new random string ID.

The generated ID is uniformly distributed and cryptographically strong. It is hence usable for things like secretkeys and access tokens.

Parameters length (int) – The length (in chars) of the ID to generate.

Returns A random string ID.

Return type str

autobahn.util.rtime()Precise, fast wallclock time.

Returns The current wallclock in seconds. Returned values are only guaranteed to be meaningfulrelative to each other.

Return type float

class autobahn.util.Stopwatch(start=True)Stopwatch based on walltime.

This can be used to do code timing and uses the most precise walltime measurement available on the platform.This is a very light-weight object, so create/dispose is very cheap.

Parameters start (bool) – If True, immediately start the stopwatch.

elapsed()Return total time elapsed in seconds during which the stopwatch was running.

Returns The elapsed time in seconds.

Return type float

pause()Pauses the stopwatch and returns total time elapsed in seconds during which the stopwatch was running.

Returns The elapsed time in seconds.

Return type float

resume()Resumes a paused stopwatch and returns total elapsed time in seconds during which the stopwatch wasrunning.

Returns The elapsed time in seconds.

Return type float

stop()Stops the stopwatch and returns total time elapsed in seconds during which the stopwatch was (previously)running.

Returns The elapsed time in seconds.

Return type float

class autobahn.util.Tracker(tracker, tracked)A key-based statistics tracker.

absolute(key)Return the UTC wall-clock time at which a tracked event occurred.

Parameters key (str) – The key

Returns Timezone-naive datetime.

9.1. Module autobahn.util 63

Page 72: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Return type instance of datetime.datetime

diff(start_key, end_key, formatted=True)Get elapsed difference between two previously tracked keys.

Parameters

• start_key (str) – First key for interval (older timestamp).

• end_key (str) – Second key for interval (younger timestamp).

• formatted (bool) – If True, format computed time period and return string.

Returns Computed time period in seconds (or formatted string).

Return type float or str

track(key)Track elapsed for key.

Parameters key (str) – Key under which to track the timing.

class autobahn.util.EqualityMixinMixing to add equality comparison operators to a class.

Two objects are identical under this mixin, if and only if:

1. both object have the same class

2. all non-private object attributes are equal

class autobahn.util.ObservableMixinInternal utility for enabling event-listeners on particular objects

fire(event, *args, **kwargs)Fire a particular event.

Parameters event – the event to fire. All other args and kwargs are passed on to the handler(s)for the event.

Returns a Deferred/Future gathering all async results from all handlers and/or parent handlers.

off(event=None, handler=None)Stop listening for a single event, or all events.

Parameters

• event – if None, remove all listeners. Otherwise, remove listeners for the single namedevent.

• handler – if None, remove all handlers for the named event; otherwise remove just thegiven handler.

on(event, handler)Add a handler for an event.

Parameters

• event – the name of the event

• handler – a callable thats invoked when .fire() is called for this events. Arguments willbe whatever are given to .fire()

set_valid_events(valid_events=None)

Parameters valid_events – if non-None, .on() or .fire() with an event not listed invalid_events raises an exception.

64 Chapter 9. API Reference

Page 73: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.util.IdGeneratorID generator for WAMP request IDs.

WAMP request IDs are sequential per WAMP session, starting at 1 and wrapping around at 2**53 (both valueare inclusive [1, 2**53]).

The upper bound 2**53 is chosen since it is the maximum integer that can be represented as a IEEE double suchthat all smaller integers are representable as well.

Hence, IDs can be safely used with languages that use IEEE double as their main (or only) number type(JavaScript, Lua, etc).

See https://github.com/wamp-proto/wamp-proto/blob/master/spec/basic.md#ids

next()Returns next ID.

Returns The next ID.

Return type int

autobahn.util.generate_token(char_groups, chars_per_group, chars=None, sep=None,lower_case=False)

Generate cryptographically strong tokens, which are strings like M6X5-YO5W-T5IK. These can be used e.g. forused-only-once activation tokens or the like.

The returned token has an entropy of math.log(len(chars), 2.) * chars_per_group *char_groups bits.

With the default charset and 4 characters per group, generate_token() produces strings with the followingentropy:

character groups entropy (at least) recommended use2 38 bits3 57 bits one-time activation or pairing code4 76 bits secure user password5 95 bits6 114 bits globally unique serial / product code7 133 bits

Here are some examples:

• token(3): 9QXT-UXJW-7R4H

• token(4): LPNN-JMET-KWEP-YK45

• token(6): NXW9-74LU-6NUH-VLPV-X6AG-QUE3

Parameters

• char_groups (int) – Number of character groups (or characters if chars_per_group ==1).

• chars_per_group (int) – Number of characters per character group (or 1 to return atoken with no grouping).

• chars (str or None) – Characters to choose from. Default is 27 character subset ofthe ISO basic Latin alphabet (see: DEFAULT_TOKEN_CHARS).

• sep (str) – When separating groups in the token, the separater string.

• lower_case (bool) – If True, generate token in lower-case.

9.1. Module autobahn.util 65

Page 74: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Returns The generated token.

Return type str

autobahn.util.generate_activation_code()Generate a one-time activation code or token of the form u'W97F-96MJ-YGJL'. The generated value iscryptographically strong and has (at least) 57 bits of entropy.

Returns The generated activation code.

Return type str

autobahn.util.generate_serial_number()Generate a globally unique serial / product code of the form u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'.The generated value is cryptographically strong and has (at least) 114 bits of entropy.

Returns The generated serial number / product code.

Return type str

autobahn.util.generate_user_password()Generate a secure, random user password of the form u'kgojzi61dn5dtb6d'. The generated value iscryptographically strong and has (at least) 76 bits of entropy.

Returns The generated password.

Return type str

9.2 Module autobahn.websocket

9.2.1 WebSocket Interfaces

class autobahn.websocket.interfaces.IWebSocketChannelA WebSocket channel is a bidirectional, full-duplex, ordered, reliable message channel over a WebSocket con-nection as specified in RFC6455.

This interface defines a message-based API to WebSocket plus auxiliary hooks and methods.

onClose(wasClean, code, reason)Callback fired when the WebSocket connection has been closed (WebSocket closing handshake has beenfinished or the connection was closed uncleanly).

Parameters

• wasClean (bool) – True iff the WebSocket connection was closed cleanly.

• code (int or None) – Close status code as sent by the WebSocket peer.

• reason (str or None) – Close reason as sent by the WebSocket peer.

onConnect(request_or_response)Callback fired during WebSocket opening handshake when a client connects (to a server with request fromclient) or when server connection established (by a client with response from server). This method mayrun asynchronous code.

Parameters request_or_response (Instance of autobahn.websocket.types.ConnectionRequest or autobahn.websocket.types.ConnectionResponse.) – Connection request (for servers) or response (for clients).

66 Chapter 9. API Reference

Page 75: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Returns When this callback is fired on a WebSocket server, you may return either None (inwhich case the connection is accepted with no specific WebSocket subprotocol) or an strinstance with the name of the WebSocket subprotocol accepted. When the callback is fired ona WebSocket client, this method must return None. To deny a connection, raise an Exception.You can also return a Deferred/Future that resolves/rejects to the above.

onConnecting(transport_details)This method is called when we’ve connected, but before the handshake is done.

Parameters transport_details (autobahn.websocket.types.TransportDetails) – information about the transport.

Returns A autobahn.websocket.types.ConnectingRequest instance is returnedto indicate which options should be used for this connection. If you wish to use the defaultbehavior, None may be returned (this is the default).

onMessage(payload, isBinary)Callback fired when a complete WebSocket message was received.

Parameters

• payload (bytes) – The WebSocket message received.

• isBinary (bool) – Flag indicating whether payload is binary or UTF-8 encoded text.

onOpen()Callback fired when the initial WebSocket opening handshake was completed. You now can send andreceive WebSocket messages.

onPing(payload)Callback fired when a WebSocket ping was received. A default implementation responds by sending aWebSocket pong.

Parameters payload (bytes) – Payload of ping (when there was any). Can be arbitrary, upto 125 octets.

onPong(payload)Callback fired when a WebSocket pong was received. A default implementation does nothing.

Parameters payload (bytes) – Payload of pong (when there was any). Can be arbitrary, upto 125 octets.

sendClose(code=None, reason=None)Starts a WebSocket closing handshake tearing down the WebSocket connection.

Parameters

• code (int) – An optional close status code (1000 for normal close or 3000-4999 forapplication specific close).

• reason (str) – An optional close reason (a string that when present, a status codeMUST also be present).

sendMessage(payload, isBinary)Send a WebSocket message over the connection to the peer.

Parameters

• payload (bytes) – The WebSocket message to be sent.

• isBinary (bool) – Flag indicating whether payload is binary or UTF-8 encoded text.

sendPing(payload=None)Send a WebSocket ping to the peer.

9.2. Module autobahn.websocket 67

Page 76: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

A peer is expected to pong back the payload a soon as “practical”. When more than one ping is outstandingat a peer, the peer may elect to respond only to the last ping.

Parameters payload (bytes or None) – An (optional) arbitrary payload of length lessthan 126 octets.

sendPong(payload=None)Send a WebSocket pong to the peer.

A WebSocket pong may be sent unsolicited. This serves as a unidirectional heartbeat. A response to anunsolicited pong is “not expected”.

Parameters payload (bytes) – An (optional) arbitrary payload of length < 126 octets.

class autobahn.websocket.interfaces.IWebSocketServerChannelFactory(url=None,proto-cols=None,server=None,head-ers=None,external-Port=None)

WebSocket server protocol factories implement this interface, and create protocol instances which in turn im-plement autobahn.websocket.interfaces.IWebSocketChannel.

Parameters

• url (str) – The WebSocket URL this factory is working for, e.g. ws://myhost.com/somepath. For non-TCP transports like pipes or Unix domain sockets, provide None.This will use an implicit URL of ws://localhost.

• protocols (list of str) – List of subprotocols the server supports. The subprotocolused is the first from the list of subprotocols announced by the client that is contained in thislist.

• server (str) – Server as announced in HTTP response header during opening handshake.

• headers (dict) – An optional mapping of additional HTTP headers to send during theWebSocket opening handshake.

• externalPort (int) – Optionally, the external visible port this server will be reachableunder (i.e. when running behind a L2/L3 forwarding device).

resetProtocolOptions()Reset all WebSocket protocol options to defaults.

setProtocolOptions(versions=None, webStatus=None, utf8validateIncoming=None, maskServer-Frames=None, requireMaskedClientFrames=None, applyMask=None,maxFramePayloadSize=None, maxMessagePayloadSize=None, aut-oFragmentSize=None, failByDrop=None, echoCloseCodeReason=None,openHandshakeTimeout=None, closeHandshakeTimeout=None, tcpN-oDelay=None, perMessageCompressionAccept=None, autoPingInter-val=None, autoPingTimeout=None, autoPingSize=None, serveFlash-SocketPolicy=None, flashSocketPolicy=None, allowedOrigins=None,allowNullOrigin=False, maxConnections=None, trustXForwardedFor=0)

Set WebSocket protocol options used as defaults for new protocol instances.

Parameters

• versions (list of ints or None) – The WebSocket protocol ver-sions accepted by the server (default: autobahn.websocket.protocol.WebSocketProtocol.SUPPORTED_PROTOCOL_VERSIONS()).

68 Chapter 9. API Reference

Page 77: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• webStatus (bool or None) – Return server status/version on HTTP/GET withoutWebSocket upgrade header (default: True).

• utf8validateIncoming (bool or None) – Validate incoming UTF-8 in textmessage payloads (default: True).

• maskServerFrames (bool or None) – Mask server-to-client frames (default:False).

• requireMaskedClientFrames (bool or None) – Require client-to-serverframes to be masked (default: True).

• applyMask (bool or None) – Actually apply mask to payload when mask it present.Applies for outgoing and incoming frames (default: True).

• maxFramePayloadSize (int or None) – Maximum frame payload size that willbe accepted when receiving or 0 for unlimited (default: 0).

• maxMessagePayloadSize (int or None) – Maximum message payload size (af-ter reassembly of fragmented messages) that will be accepted when receiving or 0 forunlimited (default: 0).

• autoFragmentSize (int or None) – Automatic fragmentation of outgoing datamessages (when using the message-based API) into frames with payload length <= thissize or 0 for no auto-fragmentation (default: 0).

• failByDrop – Fail connections by dropping the TCP connection without performingclosing handshake (default: True).

• echoCloseCodeReason (bool or None) – Iff true, when receiving a close, echoback close code/reason. Otherwise reply with code == 1000, reason = “” (default: False).

• openHandshakeTimeout (float or None) – Opening WebSocket handshaketimeout, timeout in seconds or 0 to deactivate (default: 0).

• closeHandshakeTimeout (float or None) – When we expect to receive a clos-ing handshake reply, timeout in seconds (default: 1).

• tcpNoDelay (bool or None) – TCP NODELAY (“Nagle”) socket option (default:True).

• perMessageCompressionAccept (callable or None) – Acceptor functionfor offers.

• autoPingInterval (float or None) – Automatically send WebSocket pings ev-ery given seconds. When the peer does not respond in autoPingTimeout, drop the connec-tion. Set to 0 to disable. (default: 0).

• autoPingTimeout (float or None) – Wait this many seconds for the peer to re-spond to automatically sent pings. If the peer does not respond in time, drop the connec-tion. Set to 0 to disable. (default: 0).

• autoPingSize (int or None) – Payload size for automatic pings/pongs. Must bean integer from [4, 125]. (default: 4).

• serveFlashSocketPolicy (bool or None) – Serve the Flash Socket Policywhen we receive a policy file request on this protocol. (default: False).

• flashSocketPolicy (str or None) – The flash socket policy to be served whenwe are serving the Flash Socket Policy on this protocol and when Flash tried to connect tothe destination port. It must end with a null character.

9.2. Module autobahn.websocket 69

Page 78: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• allowedOrigins (list or None) – A list of allowed WebSocket origins (with ‘*’as a wildcard character).

• allowNullOrigin (bool) – if True, allow WebSocket connections whose Origin: is“null”.

• maxConnections (int or None) – Maximum number of concurrent connections.Set to 0 to disable (default: 0).

• trustXForwardedFor (int) – Number of trusted web servers in front of this serverthat add their own X-Forwarded-For header (default: 0)

setSessionParameters(url=None, protocols=None, server=None, headers=None, external-Port=None)

Set WebSocket session parameters.

Parameters

• url (str) – The WebSocket URL this factory is working for, e.g. ws://myhost.com/somepath. For non-TCP transports like pipes or Unix domain sockets, provideNone. This will use an implicit URL of ws://localhost.

• protocols (list of str) – List of subprotocols the server supports. The subproto-col used is the first from the list of subprotocols announced by the client that is containedin this list.

• server (str) – Server as announced in HTTP response header during opening hand-shake.

• headers (dict) – An optional mapping of additional HTTP headers to send during theWebSocket opening handshake.

• externalPort (int) – Optionally, the external visible port this server will be reachableunder (i.e. when running behind a L2/L3 forwarding device).

class autobahn.websocket.interfaces.IWebSocketClientChannelFactory(url=None,ori-gin=None,proto-cols=None,usera-gent=None,head-ers=None,proxy=None)

WebSocket client protocol factories implement this interface, and create protocol instances which in turn imple-ment autobahn.websocket.interfaces.IWebSocketChannel.

Note that you MUST provide URL either here or set using autobahn.websocket.WebSocketClientFactory.setSessionParameters() before the factory is started.

Parameters

• url (str) – WebSocket URL this factory will connect to, e.g. ws://myhost.com/somepath?param1=23. For non-TCP transports like pipes or Unix domain sockets,provide None. This will use an implicit URL of ws://localhost.

• origin (str) – The origin to be sent in WebSocket opening handshake or None (default:None).

• protocols (list of strings) – List of subprotocols the client should announce inWebSocket opening handshake (default: []).

70 Chapter 9. API Reference

Page 79: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• useragent (str) – User agent as announced in HTTP request header or None (default:AutobahnWebSocket/?.?.?).

• headers (dict) – An optional mapping of additional HTTP headers to send during theWebSocket opening handshake.

• proxy (dict or None) – Explicit proxy server to use; a dict with host and port keys

resetProtocolOptions()Reset all WebSocket protocol options to defaults.

setProtocolOptions(version=None, utf8validateIncoming=None, acceptMaskedServer-Frames=None, maskClientFrames=None, applyMask=None, maxFramePay-loadSize=None, maxMessagePayloadSize=None, autoFragmentSize=None,failByDrop=None, echoCloseCodeReason=None, serverConnectionDrop-Timeout=None, openHandshakeTimeout=None, closeHandshakeTime-out=None, tcpNoDelay=None, perMessageCompressionOffers=None,perMessageCompressionAccept=None, autoPingInterval=None, autoPing-Timeout=None, autoPingSize=None)

Set WebSocket protocol options used as defaults for _new_ protocol instances.

Parameters

• version (int) – The WebSocket protocol spec (draft) version to be used(default: autobahn.websocket.protocol.WebSocketProtocol.SUPPORTED_PROTOCOL_VERSIONS()).

• utf8validateIncoming (bool) – Validate incoming UTF-8 in text message pay-loads (default: True).

• acceptMaskedServerFrames (bool) – Accept masked server-to-client frames (de-fault: False).

• maskClientFrames (bool) – Mask client-to-server frames (default: True).

• applyMask (bool) – Actually apply mask to payload when mask it present. Appliesfor outgoing and incoming frames (default: True).

• maxFramePayloadSize (int) – Maximum frame payload size that will be acceptedwhen receiving or 0 for unlimited (default: 0).

• maxMessagePayloadSize (int) – Maximum message payload size (after reassem-bly of fragmented messages) that will be accepted when receiving or 0 for unlimited (de-fault: 0).

• autoFragmentSize (int) – Automatic fragmentation of outgoing data messages(when using the message-based API) into frames with payload length <= this size or 0for no auto-fragmentation (default: 0).

• failByDrop – Fail connections by dropping the TCP connection without performingclosing handshake (default: True).

• echoCloseCodeReason (bool) – Iff true, when receiving a close, echo back closecode/reason. Otherwise reply with code == 1000, reason = “” (default: False).

• serverConnectionDropTimeout (float) – When the client expects the server todrop the TCP, timeout in seconds (default: 1).

• openHandshakeTimeout (float) – Opening WebSocket handshake timeout, time-out in seconds or 0 to deactivate (default: 0).

• closeHandshakeTimeout (float) – When we expect to receive a closing hand-shake reply, timeout in seconds (default: 1).

9.2. Module autobahn.websocket 71

Page 80: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• tcpNoDelay (bool) – TCP NODELAY (“Nagle”): bool socket option (default: True).

• perMessageCompressionOffers (list of instance of subclass ofPerMessageCompressOffer) – A list of offers to provide to the server for thepermessage-compress WebSocket extension. Must be a list of instances of subclass ofPerMessageCompressOffer.

• perMessageCompressionAccept (callable) – Acceptor function for responses.

• autoPingInterval (float or None) – Automatically send WebSocket pings ev-ery given seconds. When the peer does not respond in autoPingTimeout, drop the connec-tion. Set to 0 to disable. (default: 0).

• autoPingTimeout (float or None) – Wait this many seconds for the peer to re-spond to automatically sent pings. If the peer does not respond in time, drop the connec-tion. Set to 0 to disable. (default: 0).

• autoPingSize (int) – Payload size for automatic pings/pongs. Must be an integerfrom [4, 125]. (default: 4).

setSessionParameters(url=None, origin=None, protocols=None, useragent=None, head-ers=None, proxy=None)

Set WebSocket session parameters.

Parameters

• url (str) – WebSocket URL this factory will connect to, e.g.ws://myhost.com/somepath?param1=23. For non-TCP transports like pipes or Unixdomain sockets, provide None. This will use an implicit URL of ws://localhost.

• origin (str) – The origin to be sent in opening handshake.

• protocols (list of strings) – List of WebSocket subprotocols the client shouldannounce in opening handshake.

• useragent (str) – User agent as announced in HTTP request header during openinghandshake.

• headers (dict) – An optional mapping of additional HTTP headers to send during theWebSocket opening handshake.

• proxy (dict or None) – (Optional) a dict with host and port keys specifying aproxy to use

9.2.2 WebSocket Types

class autobahn.websocket.types.ConnectionRequest(peer, headers, host, path, params,version, origin, protocols, exten-sions)

Thin-wrapper for WebSocket connection request information provided in autobahn.websocket.protocol.WebSocketServerProtocol.onConnect() when a WebSocket client want to establisha connection to a WebSocket server.

Parameters

• peer (str) – Descriptor of the connecting client (e.g. IP address/port in case of TCPtransports).

• headers (dict) – HTTP headers from opening handshake request.

• host (str) – Host from opening handshake HTTP header.

72 Chapter 9. API Reference

Page 81: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• path (str) – Path from requested HTTP resource URI. For example, a resource URI of/myservice?foo=23&foo=66&bar=2 will be parsed to /myservice.

• params (dict) – Query parameters (if any) from requested HTTP resource URI. Forexample, a resource URI of /myservice?foo=23&foo=66&bar=2 will be parsed to{'foo': ['23', '66'], 'bar': ['2']}.

• version (int) – The WebSocket protocol version the client announced (and will be spo-ken, when connection is accepted).

• origin (str) – The WebSocket origin header or None. Note that this only a reliablesource of information for browser clients!

• protocols (list) – The WebSocket (sub)protocols the client announced. Youmust select and return one of those (or None) in autobahn.websocket.WebSocketServerProtocol.onConnect().

• extensions (list) – The WebSocket extensions the client requested and the server ac-cepted, and thus will be spoken, once the WebSocket connection has been fully established.

class autobahn.websocket.types.ConnectionResponse(peer, headers, version, protocol, ex-tensions)

Thin-wrapper for WebSocket connection response information provided in autobahn.websocket.protocol.WebSocketClientProtocol.onConnect() when a WebSocket server has accepted aconnection request by a client.

Constructor.

Parameters

• peer (str) – Descriptor of the connected server (e.g. IP address/port in case of TCPtransport).

• headers (dict) – HTTP headers from opening handshake response.

• version (int) – The WebSocket protocol version that is spoken.

• protocol (str) – The WebSocket (sub)protocol in use.

• extensions (list of str) – The WebSocket extensions in use.

class autobahn.websocket.types.ConnectionAccept(subprotocol=None, headers=None)Used by WebSocket servers to accept an incoming WebSocket connection. If the client announced one ormultiple subprotocols, the server MUST select one of the subprotocols announced by the client.

Parameters

• subprotocol (unicode or None) – The WebSocket connection is accepted with thethis WebSocket subprotocol chosen. The value must be a token as defined by RFC 2616.

• headers (dict or None) – Additional HTTP headers to send on the WebSocket open-ing handshake reply, e.g. cookies. The keys must be unicode, and the values either unicodeor tuple/list. In the latter case a separate HTTP header line will be sent for each item intuple/list.

exception autobahn.websocket.types.ConnectionDeny(code, reason=None)Throw an instance of this class to deny a WebSocket connection during handshake in autobahn.websocket.protocol.WebSocketServerProtocol.onConnect().

Parameters

• code (int) – HTTP error code.

• reason (unicode) – HTTP error reason.

9.2. Module autobahn.websocket 73

Page 82: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

BAD_REQUEST = 400Bad Request. The request cannot be fulfilled due to bad syntax.

FORBIDDEN = 403Forbidden. The request was a legal request, but the server is refusing to respond to it.[2] Unlike a 401Unauthorized response, authenticating will make no difference.

INTERNAL_SERVER_ERROR = 500Internal Server Error. A generic error message, given when no more specific message is suitable.

NOT_ACCEPTABLE = 406Not Acceptable. The requested resource is only capable of generating content not acceptable according tothe Accept headers sent in the request.

NOT_FOUND = 404Not Found. The requested resource could not be found but may be available again in the future.[2] Subse-quent requests by the client are permissible.

NOT_IMPLEMENTED = 501Not Implemented. The server either does not recognize the request method, or it lacks the ability to fulfillthe request.

REQUEST_TIMEOUT = 408Request Timeout. The server timed out waiting for the request. According to W3 HTTP specifications:‘The client did not produce a request within the time that the server was prepared to wait. The client MAYrepeat the request without modifications at any later time.

SERVICE_UNAVAILABLE = 503Service Unavailable. The server is currently unavailable (because it is overloaded or down for mainte-nance). Generally, this is a temporary state.

class autobahn.websocket.types.MessageAbstract base class for WebSocket messages.

class autobahn.websocket.types.IncomingMessage(payload, is_binary=False)An incoming WebSocket message.

Parameters

• payload (bytes) – The WebSocket message payload, which can be UTF-8 encoded textor a binary string.

• is_binary (bool) – True for binary payload, else the payload contains UTF-8 encodedtext.

class autobahn.websocket.types.OutgoingMessage(payload, is_binary=False,skip_compress=False)

An outgoing WebSocket message.

Parameters

• payload (bytes) – The WebSocket message payload, which can be UTF-8 encoded textor a binary string.

• is_binary (bool) – True iff payload is binary, else the payload contains UTF-8 en-coded text.

• skip_compress (bool) – If True, never compress this message. This only has an effectwhen WebSocket compression has been negotiated on the WebSocket connection. Use whenyou know the payload is incompressible (e.g. encrypted or already compressed).

74 Chapter 9. API Reference

Page 83: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

9.2.3 WebSocket Compression

class autobahn.websocket.compress.PerMessageCompressOfferBase class for WebSocket compression parameter client offers.

class autobahn.websocket.compress.PerMessageCompressOfferAcceptBase class for WebSocket compression parameter client offer accepts by the server.

class autobahn.websocket.compress.PerMessageCompressResponseBase class for WebSocket compression parameter server responses.

class autobahn.websocket.compress.PerMessageCompressResponseAcceptBase class for WebSocket compression parameter server response accepts by client.

class autobahn.websocket.compress.PerMessageCompressBase class for WebSocket compression negotiated parameters.

class autobahn.websocket.compress.PerMessageDeflateOffer(accept_no_context_takeover=True,ac-cept_max_window_bits=True,re-quest_no_context_takeover=False,re-quest_max_window_bits=0)

Set of extension parameters for permessage-deflate WebSocket extension offered by a client to a server.

Parameters

• accept_no_context_takeover (bool) – When True, the client accepts the “nocontext takeover” feature.

• accept_max_window_bits (bool) – When True, the client accepts setting “maxwindow size”.

• request_no_context_takeover (bool) – When True, the client request the “nocontext takeover” feature.

• request_max_window_bits (int) – When non-zero, the client requests the given“max window size” (must be and integer from the interval [8..15]).

get_extension_string()Returns the WebSocket extension configuration string as sent to the server.

Returns PMCE configuration string.

Return type str

classmethod parse(params)Parses a WebSocket extension offer for permessage-deflate provided by a client to a server.

Parameters params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns A new instance of autobahn.compress.PerMessageDeflateOffer.

Return type obj

9.2. Module autobahn.websocket 75

Page 84: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.websocket.compress.PerMessageDeflateOfferAccept(offer, re-quest_no_context_takeover=False,re-quest_max_window_bits=0,no_context_takeover=None,win-dow_bits=None,mem_level=None,max_message_size=None)

Set of parameters with which to accept an permessage-deflate offer from a client by a server.

Parameters

• offer (Instance of autobahn.compress.PerMessageDeflateOffer.) – Theoffer being accepted.

• request_no_context_takeover (bool) – When True, the server requests the “nocontext takeover” feature.

• request_max_window_bits – When non-zero, the server requests the given “maxwindow size” (must be and integer from the interval [8..15]).

• request_max_window_bits – int

• no_context_takeover (bool) – Override server (“server-to-client direction”) contexttakeover (this must be compatible with the offer).

• window_bits (int) – Override server (“server-to-client direction”) window size (thismust be compatible with the offer).

• mem_level (int) – Set server (“server-to-client direction”) memory level.

get_extension_string()Returns the WebSocket extension configuration string as sent to the server.

Returns PMCE configuration string.

Return type str

class autobahn.websocket.compress.PerMessageDeflateResponse(client_max_window_bits,client_no_context_takeover,server_max_window_bits,server_no_context_takeover)

Set of parameters for permessage-deflate responded by server.

Parameters

• client_max_window_bits (int) – FIXME

• client_no_context_takeover (bool) – FIXME

• server_max_window_bits (int) – FIXME

• server_no_context_takeover (bool) – FIXME

classmethod parse(params)Parses a WebSocket extension response for permessage-deflate provided by a server to a client.

Parameters params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns A new instance of autobahn.compress.PerMessageDeflateResponse.

Return type obj

76 Chapter 9. API Reference

Page 85: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.websocket.compress.PerMessageDeflateResponseAccept(response,no_context_takeover=None,win-dow_bits=None,mem_level=None,max_message_size=None)

Set of parameters with which to accept an permessage-deflate response from a server by a client.

Parameters

• response (Instance of autobahn.compress.PerMessageDeflateResponse.)– The response being accepted.

• no_context_takeover (bool) – Override client (“client-to-server direction”) contexttakeover (this must be compatible with response).

• window_bits (int) – Override client (“client-to-server direction”) window size (thismust be compatible with response).

• mem_level (int) – Set client (“client-to-server direction”) memory level.

class autobahn.websocket.compress.PerMessageDeflate(is_server,server_no_context_takeover,client_no_context_takeover,server_max_window_bits,client_max_window_bits,mem_level,max_message_size=None)

permessage-deflate WebSocket extension processor.

class autobahn.websocket.compress.PerMessageBzip2Offer(accept_max_compress_level=True,re-quest_max_compress_level=0)

Set of extension parameters for permessage-bzip2 WebSocket extension offered by a client to a server.

Constructor.

Parameters

• accept_max_compress_level (bool) – Iff true, client accepts “maximum compres-sion level” parameter.

• request_max_compress_level (int) – Iff non-zero, client requests given “maxi-mum compression level” - must be 1-9.

get_extension_string()Returns the WebSocket extension configuration string as sent to the server.

Returns PMCE configuration string.

Return type str

classmethod parse(params)Parses a WebSocket extension offer for permessage-bzip2 provided by a client to a server.

Parameters params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns object – A new instance of autobahn.compress.PerMessageBzip2Offer.

9.2. Module autobahn.websocket 77

Page 86: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.websocket.compress.PerMessageBzip2OfferAccept(offer, re-quest_max_compress_level=0,com-press_level=None)

Set of parameters with which to accept an permessage-bzip2 offer from a client by a server.

Constructor.

Parameters

• offer (Instance of autobahn.compress.PerMessageBzip2Offer.) – The offerbeing accepted.

• request_max_compress_level (int) – Iff non-zero, server requests given “maxi-mum compression level” - must be 1-9.

• compress_level (int) – Override server (“server-to-client direction”) compress level(this must be compatible with offer).

get_extension_string()Returns the WebSocket extension configuration string as sent to the server.

Returns PMCE configuration string.

Return type str

class autobahn.websocket.compress.PerMessageBzip2Response(client_max_compress_level,server_max_compress_level)

Set of parameters for permessage-bzip2 responded by server.

classmethod parse(params)Parses a WebSocket extension response for permessage-bzip2 provided by a server to a client.

Parameters params (list) – Output from autobahn.websocket.WebSocketProtocol._parseExtensionsHeader().

Returns A new instance of autobahn.compress.PerMessageBzip2Response.

Return type obj

class autobahn.websocket.compress.PerMessageBzip2ResponseAccept(response, com-press_level=None)

Set of parameters with which to accept an permessage-bzip2 response from a server by a client.

Parameters

• response (Instance of autobahn.compress.PerMessageBzip2Response.) –The response being accepted.

• compress_level (int) – Override client (“client-to-server direction”) compress level(this must be compatible with response).

class autobahn.websocket.compress.PerMessageBzip2(is_server,server_max_compress_level,client_max_compress_level)

permessage-bzip2 WebSocket extension processor.

9.2.4 WebSocket Utilities

WebSocket utilities that do not depend on the specific networking framework being used (Twisted or asyncio).

78 Chapter 9. API Reference

Page 87: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

autobahn.websocket.util.create_url(hostname, port=None, isSecure=False, path=None,params=None)

Create a WebSocket URL from components.

Parameters

• hostname (str) – WebSocket server hostname (for TCP/IP sockets) or filesystem path(for Unix domain sockets).

• port (int or str) – For TCP/IP sockets, WebSocket service port or None (to selectdefault ports 80 or 443 depending on isSecure. When hostname=="unix", thisdefines the path to the Unix domain socket instead of a TCP/IP network socket.

• isSecure (bool) – Set True for secure WebSocket (wss scheme).

• path (str) – WebSocket URL path of addressed resource (will be properly URL escaped).Ignored for RawSocket.

• params (dict) – A dictionary of key-values to construct the query component of theaddressed WebSocket resource (will be properly URL escaped). Ignored for RawSocket.

Returns Constructed WebSocket URL.

Return type str

autobahn.websocket.util.parse_url(url)Parses as WebSocket URL into it’s components and returns a tuple:

• isSecure is a flag which is True for wss URLs.

• host is the hostname or IP from the URL.

and for TCP/IP sockets:

• tcp_port is the port from the URL or standard port derived from scheme (rs => 80, rss => 443).

or for Unix domain sockets:

• uds_path is the path on the local host filesystem.

Parameters url (str) – A valid WebSocket URL, i.e. ws://localhost:9000 for TCP/IPsockets or ws://unix:/tmp/file.sock for Unix domain sockets (UDS).

Returns A 6-tuple (isSecure, host, tcp_port, resource, path, params)(TCP/IP) or (isSecure, host, uds_path, resource, path, params) (UDS).

Return type tuple

9.3 Module autobahn.rawsocket

WAMP-RawSocket is an alternative WAMP transport that has less overhead compared to WebSocket, and is vastlysimpler to implement. It can run over any stream based underlying transport, such as TCP or Unix domain socket.However, it does NOT run into the browser.

9.3.1 RawSocket Utilities

RawSocket utilities that do not depend on the specific networking framework being used (Twisted or asyncio).

autobahn.rawsocket.util.create_url(hostname, port=None, isSecure=False)Create a RawSocket URL from components.

9.3. Module autobahn.rawsocket 79

Page 88: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Parameters

• hostname (str) – RawSocket server hostname (for TCP/IP sockets) or filesystem path(for Unix domain sockets).

• port (int or str) – For TCP/IP sockets, RawSocket service port or None (to selectdefault ports 80 or 443 depending on isSecure. When hostname=="unix", thisdefines the path to the Unix domain socket instead of a TCP/IP network socket.

• isSecure (bool) – Set True for secure RawSocket (rss scheme).

Returns Constructed RawSocket URL.

Return type str

autobahn.rawsocket.util.parse_url(url)Parses as RawSocket URL into it’s components and returns a tuple:

• isSecure is a flag which is True for rss URLs.

• host is the hostname or IP from the URL.

and for TCP/IP sockets:

• tcp_port is the port from the URL or standard port derived from scheme (rs => 80, rss => 443).

or for Unix domain sockets:

• uds_path is the path on the local host filesystem.

Parameters url (str) – A valid RawSocket URL, i.e. rs://localhost:9000 for TCP/IPsockets or rs://unix:/tmp/file.sock for Unix domain sockets (UDS).

Returns A 3-tuple (isSecure, host, tcp_port) (TCP/IP) or (isSecure, host,uds_path) (UDS).

Return type tuple

9.4 Module autobahn.wamp

9.4.1 WAMP Interfaces

class autobahn.wamp.interfaces.IObjectSerializerRaw Python object serialization and deserialization. Object serializers are used by classes implementing WAMPserializers, that is instances of autobahn.wamp.interfaces.ISerializer.

BINARYFlag (read-only) to indicate if serializer requires a binary clean transport or if UTF8 transparency is suffi-cient.

serialize(obj)Serialize an object to a byte string.

Parameters obj (any (serializable type)) – Object to serialize.

Returns Serialized bytes.

Return type bytes

unserialize(payload)Unserialize objects from a byte string.

80 Chapter 9. API Reference

Page 89: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Parameters payload (bytes) – Objects to unserialize.

Returns List of (raw) objects unserialized.

Return type list

class autobahn.wamp.interfaces.ISerializerWAMP message serialization and deserialization.

MESSAGE_TYPE_MAPMapping of WAMP message type codes to WAMP message classes.

SERIALIZER_IDThe WAMP serialization format ID.

serialize(message)Serializes a WAMP message to bytes for sending over a transport.

Parameters message (object implementing autobahn.wamp.interfaces.IMessage) – The WAMP message to be serialized.

Returns A pair (payload, isBinary).

Return type tuple

unserialize(payload, isBinary)Deserialize bytes from a transport and parse into WAMP messages.

Parameters

• payload (bytes) – Byte string from wire.

• is_binary (bool) – Type of payload. True if payload is a binary string, else the pay-load is UTF-8 encoded Unicode text.

Returns List of a.w.m.Message objects.

Return type list

class autobahn.wamp.interfaces.IMessage

MESSAGE_TYPEWAMP message type code.

static parse(wmsg)Factory method that parses a unserialized raw message (as returned byte autobahn.interfaces.ISerializer.unserialize()) into an instance of this class.

Returns The parsed WAMP message.

Return type object implementing autobahn.wamp.interfaces.IMessage

serialize(serializer)Serialize this object into a wire level bytes representation and cache the resulting bytes. If the cache alreadycontains an entry for the given serializer, return the cached representation directly.

Parameters serializer (object implementing autobahn.wamp.interfaces.ISerializer) – The wire level serializer to use.

Returns The serialized bytes.

Return type bytes

uncache()Resets the serialization cache for this message.

9.4. Module autobahn.wamp 81

Page 90: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.wamp.interfaces.ITransportA WAMP transport is a bidirectional, full-duplex, reliable, ordered, message-based channel.

abort()Abort the transport abruptly. The transport will be destroyed as fast as possible, and without playing niceto the peer. This should only be used in case of fatal errors, protocol violations or possible detected attacks.

close()Close the transport regularly. The transport will perform any closing handshake if applicable. This shouldbe used for any application initiated closing.

get_channel_id()Return the unique channel ID of the underlying transport. This is used to mitigate credential forwardingman-in-the-middle attacks when running application level authentication (eg WAMP-cryptosign) whichare decoupled from the underlying transport.

The channel ID is only available when running over TLS (either WAMP-WebSocket or WAMP-RawSocket). It is not available for non-TLS transports (plain TCP or Unix domain sockets). It is alsonot available for WAMP-over-HTTP/Longpoll. Further, it is currently unimplemented for asyncio (onlyworks on Twisted).

The channel ID is computed as follows:

• for a client, the SHA256 over the “TLS Finished” message sent by the client to the server is returned.

• for a server, the SHA256 over the “TLS Finished” message the server expected the client to send

Note: this is similar to tls-unique as described in RFC5929, but instead of returning the raw “TLS Finished”message, it returns a SHA256 over such a message. The reason is that we use the channel ID mainly withWAMP-cryptosign, which is based on Ed25519, where keys are always 32 bytes. And having a channelID which is always 32 bytes (independent of the TLS ciphers/hashfuns in use) allows use to easily XORchannel IDs with Ed25519 keys and WAMP-cryptosign challenges.

WARNING: For safe use of this (that is, for safely binding app level authentication to the underlyingtransport), you MUST use TLS, and you SHOULD deactivate both TLS session renegotiation and TLSsession resumption.

References:

• https://tools.ietf.org/html/rfc5056

• https://tools.ietf.org/html/rfc5929

• http://www.pyopenssl.org/en/stable/api/ssl.html#OpenSSL.SSL.Connection.get_finished

• http://www.pyopenssl.org/en/stable/api/ssl.html#OpenSSL.SSL.Connection.get_peer_finished

Returns The channel ID (if available) of the underlying WAMP transport. The channel ID is a32 bytes value.

Return type binary or None

isOpen()Check if the transport is open for messaging.

Returns True, if the transport is open.

Return type bool

send(message)Send a WAMP message over the transport to the peer. If the transport is not open, this raises autobahn.wamp.exception.TransportLost. Returns a deferred/future when the message has been pro-

82 Chapter 9. API Reference

Page 91: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

cessed and more messages may be sent. When send() is called while a previous deferred/future has not yetfired, the send will fail immediately.

Parameters message (object implementing autobahn.wamp.interfaces.IMessage) – The WAMP message to send over the transport.

Returns obj – A Deferred/Future

class autobahn.wamp.interfaces.ISession(config=None)Interface for WAMP sessions.

Parameters config (instance of autobahn.wamp.types.ComponentConfig.) – Config-uration for session.

call(procedure, *args, **kwargs)Call a remote procedure.

This will return a Deferred/Future, that when resolved, provides the actual result returned by the calledremote procedure.

• If the result is a single positional return value, it’ll be returned “as-is”.

• If the result contains multiple positional return values or keyword return values, the result is wrappedin an instance of autobahn.wamp.types.CallResult.

• If the call fails, the returned Deferred/Future will be rejected with an instance of autobahn.wamp.exception.ApplicationError.

If kwargs contains an options keyword argument that is an instance of autobahn.wamp.types.CallOptions, this will provide specific options for the call to perform.

When the Caller and Dealer implementations support canceling of calls, the call may be canceled bycanceling the returned Deferred/Future.

Parameters

• procedure (unicode) – The URI of the remote procedure to be called, e.g. u"com.myapp.hello".

• args (list) – Any positional arguments for the call.

• kwargs (dict) – Any keyword arguments for the call.

Returns A Deferred/Future for the call result -

Return type instance of twisted.internet.defer.Deferred / asyncio.Future

define(exception, error=None)Defines an exception for a WAMP error in the context of this WAMP session.

Parameters

• exception (A class that derives of Exception.) – The exception class to define anerror mapping for.

• error (str) – The URI (or URI pattern) the exception class should be mapped for. Iffthe exception class is decorated, this must be None.

disconnect()Close the underlying transport.

get_payload_codec()Get the current payload codec (if any) for the session.

Payload codecs are used with WAMP payload transparency mode.

9.4. Module autobahn.wamp 83

Page 92: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Returns The current payload codec or None if no codec is active.

Return type object implementing autobahn.wamp.interfaces.IPayloadCodec orNone

is_attached()Check if the session has currently joined a realm.

is_connected()Check if the underlying transport is connected.

join(realm, authmethods=None, authid=None, authrole=None, authextra=None, resumable=None, re-sume_session=None, resume_token=None)

Attach the session to the given realm. A session is open as soon as it is attached to a realm.

leave(reason=None, message=None)Actively close this WAMP session.

Parameters

• reason (str) – An optional URI for the closing reason. If you want to permanently logout, this should be wamp.close.logout

• message (str) – An optional (human readable) closing message, intended for loggingpurposes.

Returns may return a Future/Deferred that fires when we’ve disconnected

onChallenge(challenge)Callback fired when the peer demands authentication.

May return a Deferred/Future.

Parameters challenge (Instance of autobahn.wamp.types.Challenge.) – The au-thentication challenge.

onConnect()Callback fired when the transport this session will run over has been established.

onDisconnect()Callback fired when underlying transport has been closed.

onJoin(details)Callback fired when WAMP session has been established.

May return a Deferred/Future.

Parameters details (Instance of autobahn.wamp.types.SessionDetails.) – Ses-sion information.

onLeave(details)Callback fired when WAMP session has is closed

Parameters details (Instance of autobahn.wamp.types.CloseDetails.) – Closeinformation.

onUserError(fail, msg)This is called when we try to fire a callback, but get an exception from user code – for example, a registeredpublish callback or a registered method. By default, this prints the current stack-trace and then error-message to stdout.

ApplicationSession-derived objects may override this to provide logging if they prefer. The Twisted im-plemention does this. (See autobahn.twisted.wamp.ApplicationSession)

Parameters

84 Chapter 9. API Reference

Page 93: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• fail (instance implementing txaio.IFailedFuture) – The failure thatoccurred.

• msg (str) – an informative message from the library. It is suggested you log this imme-diately after the exception.

onWelcome(welcome_msg)Callback fired after the peer has successfully authenticated. If this returns anything other than None/False,the session is aborted and the return value is used as an error message.

May return a Deferred/Future.

Parameters welcome_msg – The WELCOME message received from the server

Returns None, or an error message

publish(topic, *args, **kwargs)Publish an event to a topic.

If kwargs contains an options keyword argument that is an instance of autobahn.wamp.types.PublishOptions, this will provide specific options for the publish to perform.

Note: By default, publications are non-acknowledged and the publication can fail silently, e.g. becausethe session is not authorized to publish to the topic.

When publication acknowledgement is requested via options.acknowledge == True, this func-tion returns a Deferred/Future:

• If the publication succeeds the Deferred/Future will resolve to an object that implements autobahn.wamp.interfaces.IPublication.

• If the publication fails the Deferred/Future will reject with an instance of autobahn.wamp.exception.ApplicationError.

Parameters

• topic (unicode) – The URI of the topic to publish to, e.g. u"com.myapp.mytopic1".

• args (list) – Arbitrary application payload for the event (positional arguments).

• kwargs (dict) – Arbitrary application payload for the event (keyword arguments).

Returns Acknowledgement for acknowledge publications - otherwise nothing.

Return type None or instance of twisted.internet.defer.Deferred / asyncio.Future

register(endpoint, procedure=None, options=None, prefix=None)Register a procedure for remote calling.

When endpoint is a callable (function, method or object that implements __call__), thenprocedure must be provided and an instance of twisted.internet.defer.Deferred (when running onTwisted) or an instance of asyncio.Future (when running on asyncio) is returned.

• If the registration succeeds the returned Deferred/Future will resolve to an object that implementsautobahn.wamp.interfaces.IRegistration.

• If the registration fails the returned Deferred/Future will reject with an instance of autobahn.wamp.exception.ApplicationError.

9.4. Module autobahn.wamp 85

Page 94: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

When endpoint is an object, then each of the object’s methods that is decorated with autobahn.wamp.register() is automatically registered and a (single) DeferredList or Future is returned thatgathers all individual underlying Deferreds/Futures.

Parameters

• endpoint (callable or object) – The endpoint called under the procedure.

• procedure (unicode) – When endpoint is a callable, the URI (or URI pattern) ofthe procedure to register for. When endpoint is an object, the argument is ignored (andshould be None).

• options (instance of autobahn.wamp.types.RegisterOptions.) – Optionsfor registering.

• prefix (str) – if not None, this specifies a prefix to prepend to all URIs registeredfor this class. So if there was an @wamp.register(‘method_foo’) on a method and pre-fix=’com.something.’ then a method ‘com.something.method_foo’ would ultimately beregistered.

Returns A registration or a list of registrations (or errors)

Return type instance(s) of twisted.internet.defer.Deferred / asyncio.Future

set_payload_codec(payload_codec)Set a payload codec on the session. To remove a previously set payload codec, set the codec to None.

Payload codecs are used with WAMP payload transparency mode.

Parameters payload_codec (object implementing autobahn.wamp.interfaces.IPayloadCodec or None) – The payload codec that should process application payloadof the given encoding.

subscribe(handler, topic=None, options=None)Subscribe to a topic for receiving events.

When handler is a callable (function, method or object that implements __call__), then topic mustbe provided and an instance of twisted.internet.defer.Deferred (when running on Twisted) or an instanceof asyncio.Future (when running on asyncio) is returned.

• If the subscription succeeds the Deferred/Future will resolve to an object that implementsautobahn.wamp.interfaces.ISubscription.

• If the subscription fails the Deferred/Future will reject with an instance of autobahn.wamp.exception.ApplicationError.

When handler is an object, then each of the object’s methods that is decorated with autobahn.wamp.subscribe() is automatically subscribed as event handlers, and a list of Deferreds/Futures is returnedthat each resolves or rejects as above.

Parameters

• handler (callable or object) – The event handler to receive events.

• topic (unicode) – When handler is a callable, the URI (or URI pattern) of the topicto subscribe to. When handler is an object, this value is ignored (and should be None).

• options (An instance of autobahn.wamp.types.SubscribeOptions.) – Op-tions for subscribing.

Returns A single Deferred/Future or a list of such objects

Return type instance(s) of twisted.internet.defer.Deferred / asyncio.Future

86 Chapter 9. API Reference

Page 95: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.wamp.interfaces.IPayloadCodecWAMP payload codecs are used with WAMP payload transparency mode.

In payload transparency mode, application payloads are transmitted “raw”, as binary strings, without any pro-cessing at the WAMP router.

Payload transparency can be used eg for these use cases:

• end-to-end encryption of application payloads (WAMP-cryptobox)

• using serializers with custom user types, where the serializer and the serializer implementation has nativesupport for serializing custom types (such as CBOR)

• transmitting MQTT payloads within WAMP, when the WAMP router is providing a MQTT-WAMP bridge

decode(is_originating, uri, encoded_payload)Decode application payload.

Parameters

• is_originating (bool) – Flag indicating whether the encoding is to be done froman originator (a caller or publisher).

• uri (str) – The WAMP URI associated with the WAMP message for which the payloadis to be encoded (eg topic or procedure).

• payload (instance of autobahn.wamp.types.EncodedPayload) – The en-coded application payload to be decoded.

Returns A tuple with the decoded positional and keyword-based application payload: (uri,args, kwargs)

Return type tuple

encode(is_originating, uri, args=None, kwargs=None)Encodes application payload.

Parameters

• is_originating (bool) – Flag indicating whether the encoding is to be done froman originator (a caller or publisher).

• uri (str) – The WAMP URI associated with the WAMP message for which the payloadis to be encoded (eg topic or procedure).

• args (list or None) – Positional application payload.

• kwargs (dict or None) – Keyword-based application payload.

Returns The encoded application payload or None to signal no encoding should be used.

Return type instance of autobahn.wamp.types.EncodedPayload

9.4.2 WAMP Types

class autobahn.wamp.types.ComponentConfig(realm=None, extra=None, keyring=None, con-troller=None, shared=None, runner=None)

WAMP application component configuration. An instance of this class is provided to the constructor ofautobahn.wamp.protocol.ApplicationSession.

Parameters

• realm (str) – The realm the session would like to join or None to let the router auto-decide the realm (if the router is configured and allowing to do so).

9.4. Module autobahn.wamp 87

Page 96: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• extra (arbitrary) – Optional user-supplied object with extra configuration. Thiscan be any object you like, and is accessible in your ApplicationSession subclass viaself.config.extra. dict is a good default choice. Important: if the component is to be hostedby Crossbar.io, the supplied value must be JSON serializable.

• keyring (obj implementing IKeyRing or None) – A mapper from WAMPURIs to “from”/”to” Ed25519 keys. When using WAMP end-to-end encryption, applica-tion payload is encrypted using a symmetric message key, which in turn is encrypted usingthe “to” URI (topic being published to or procedure being called) public key and the “from”URI private key. In both cases, the key for the longest matching URI is used.

• controller (instance of ApplicationSession or None) – A WAMP Ap-plicationSession instance that holds a session to a controlling entity. This optional featureneeds to be supported by a WAMP component hosting run-time.

• shared (dict or None) – A dict object to exchange user information or hold userobjects shared between components run under the same controlling entity. This optionalfeature needs to be supported by a WAMP component hosting run-time. Use with caution,as using this feature can introduce coupling between components. A valid use case wouldbe to hold a shared database connection pool.

• runner (autobahn.twisted.wamp.ApplicationRunner) – Instance of Appli-cationRunner when run under this.

class autobahn.wamp.types.HelloReturnBase class for HELLO return information.

class autobahn.wamp.types.Accept(realm=None, authid=None, authrole=None, auth-method=None, authprovider=None, authextra=None)

Information to accept a HELLO.

Parameters

• realm (str) – The realm the client is joined to.

• authid (str) – The authentication ID the client is assigned, e.g. "joe" or"[email protected]".

• authrole (str) – The authentication role the client is assigned, e.g. "anonymous","user" or "com.myapp.user".

• authmethod (str) – The authentication method that was used to authenticate the client,e.g. "cookie" or "wampcra".

• authprovider (str) – The authentication provider that was used to authenticate theclient, e.g. "mozilla-persona".

• authextra (dict) – Application-specific authextra to be forwarded to the client in WEL-COME.details.authextra.

class autobahn.wamp.types.Deny(reason=u’wamp.error.not_authorized’, message=None)Information to deny a HELLO.

Parameters

• reason (str) – The reason of denying the authentication (an URI, e.g. u'wamp.error.not_authorized')

• message (str) – A human readable message (for logging purposes).

class autobahn.wamp.types.Challenge(method, extra=None)Information to challenge the client upon HELLO.

Parameters

88 Chapter 9. API Reference

Page 97: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• method (str) – The authentication method for the challenge (e.g. "wampcra").

• extra (dict) – Any extra information for the authentication challenge. This is specific tothe authentication method.

class autobahn.wamp.types.HelloDetails(realm=None, authmethods=None, authid=None, au-throle=None, authextra=None, session_roles=None,pending_session=None, resumable=None, re-sume_session=None, resume_token=None)

Provides details of a WAMP session while still attaching.

Parameters

• realm (str or None) – The realm the client wants to join.

• authmethods (list of str or None) – The authentication methods the client iswilling to perform.

• authid (str or None) – The authid the client wants to authenticate as.

• authrole (str or None) – The authrole the client wants to authenticate as.

• authextra (arbitrary or None) – Any extra information the specific authentica-tion method requires the client to send.

• session_roles (dict or None) – The WAMP session roles and features by the con-necting client.

• pending_session (int or None) – The session ID the session will get once suc-cessfully attached.

• resumable (bool or None) –

• resume_session (int or None) – The session the client would like to resume.

• resume_token (str or None) – The secure authorisation token to resume the ses-sion.

class autobahn.wamp.types.SessionDetails(realm, session, authid=None, authrole=None,authmethod=None, authprovider=None, authex-tra=None, serializer=None, resumed=None, re-sumable=None, resume_token=None)

Provides details for a WAMP session upon open.

See also:

autobahn.wamp.interfaces.ISession.onJoin()

Parameters

• realm (str) – The realm this WAMP session is attached to.

• session (int) – WAMP session ID of this session.

• resumed (bool or None) – Whether the session is a resumed one.

• resumable (bool or None) – Whether this session can be resumed later.

• resume_token (str or None) – The secure authorisation token to resume the ses-sion.

class autobahn.wamp.types.SessionIdent(session=None, authid=None, authrole=None)WAMP session identification information.

9.4. Module autobahn.wamp 89

Page 98: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

A WAMP session joined on a realm on a WAMP router is identified technically by its session ID (session)already.

The permissions the session has are tied to the WAMP authentication role (authrole).

The subject behind the session, eg the user or the application component is identified by the WAMP authenti-cation ID (authid). One session is always authenticated under/as one specific authid, but a given authidmight have zero, one or many sessions joined on a router at the same time.

Parameters

• session (int) – WAMP session ID of the session.

• authid (str) – The WAMP authid of the session.

• authrole (str) – The WAMP authrole of the session.

static from_calldetails(call_details)Create a new session identification object from the caller information in the call details provided.

Parameters call_details (autobahn.wamp.types.CallDetails) – Details of aWAMP call.

Returns New session identification object.

Return type autobahn.wamp.types.SessionIdent

static from_eventdetails(event_details)Create a new session identification object from the publisher information in the event details provided.

Parameters event_details (autobahn.wamp.types.EventDetails) – Details ofa WAMP event.

Returns New session identification object.

Return type autobahn.wamp.types.SessionIdent

class autobahn.wamp.types.CloseDetails(reason=None, message=None)Provides details for a WAMP session upon close.

See also:

autobahn.wamp.interfaces.ISession.onLeave()

Parameters

• reason (str) – The close reason (an URI, e.g. wamp.close.normal)

• message (str) – Closing log message.

class autobahn.wamp.types.SubscribeOptions(match=None, details=None, de-tails_arg=None, forward_for=None,get_retained=None, correlation_id=None,correlation_uri=None, correla-tion_is_anchor=None, correla-tion_is_last=None)

Used to provide options for subscribing in autobahn.wamp.interfaces.ISubscriber.subscribe().

Parameters

• match (str) – The topic matching method to be used for the subscription.

• details (bool) – When invoking the handler, provide event details in a keyword param-eter details.

90 Chapter 9. API Reference

Page 99: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• details_arg (str) – DEPCREATED (use “details” flag). When invoking the handlerprovide event details in this keyword argument to the callable.

• get_retained (bool or None) – Whether the client wants the retained message wemay have along with the subscription.

message_attr()Returns options dict as sent within WAMP messages.

class autobahn.wamp.types.EventDetails(subscription, publication, publisher=None, pub-lisher_authid=None, publisher_authrole=None,topic=None, retained=None, enc_algo=None,forward_for=None)

Provides details on an event when calling an event handler previously registered.

Parameters

• subscription (instance of autobahn.wamp.request.Subscription) – The(client side) subscription object on which this event is delivered.

• publication (int) – The publication ID of the event (always present).

• publisher (None or int) – The WAMP session ID of the original publisher of thisevent. Only filled when publisher is disclosed.

• publisher_authid (str or None) – The WAMP authid of the original publisher ofthis event. Only filled when publisher is disclosed.

• publisher_authrole (str or None) – The WAMP authrole of the original pub-lisher of this event. Only filled when publisher is disclosed.

• topic (str or None) – For pattern-based subscriptions, the actual topic URI beingpublished to. Only filled for pattern-based subscriptions.

• retained (bool or None) – Whether the message was retained by the broker on thetopic, rather than just published.

• enc_algo (str or None) – Payload encryption algorithm that was in use (currently,either None or u'cryptobox').

• forward_for (list[dict]) – When this Event is forwarded for a client (or from anintermediary router).

class autobahn.wamp.types.PublishOptions(acknowledge=None, exclude_me=None, ex-clude=None, exclude_authid=None, ex-clude_authrole=None, eligible=None, eligi-ble_authid=None, eligible_authrole=None,retain=None, forward_for=None, corre-lation_id=None, correlation_uri=None,correlation_is_anchor=None, correla-tion_is_last=None)

Used to provide options for subscribing in autobahn.wamp.interfaces.IPublisher.publish().

Parameters

• acknowledge (bool) – If True, acknowledge the publication with a success or errorresponse.

• exclude_me (bool or None) – If True, exclude the publisher from receiving theevent, even if he is subscribed (and eligible).

• exclude (int or list of int or None) – A single WAMP session ID or a listthereof to exclude from receiving this event.

9.4. Module autobahn.wamp 91

Page 100: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• exclude_authid (str or list of str or None) – A single WAMP authid ora list thereof to exclude from receiving this event.

• exclude_authrole (list of str or None) – A single WAMP authrole or a listthereof to exclude from receiving this event.

• eligible (int or list of int or None) – A single WAMP session ID or a listthereof eligible to receive this event.

• eligible_authid (str or list of str or None) – A single WAMP authidor a list thereof eligible to receive this event.

• eligible_authrole (str or list of str or None) – A single WAMP au-throle or a list thereof eligible to receive this event.

• retain (bool or None) – If True, request the broker retain this event.

• forward_for (list[dict]) – When this Event is forwarded for a client (or from anintermediary router).

message_attr()Returns options dict as sent within WAMP messages.

class autobahn.wamp.types.RegisterOptions(match=None, invoke=None, concur-rency=None, force_reregister=None,forward_for=None, details=None, de-tails_arg=None, correlation_id=None, correla-tion_uri=None, correlation_is_anchor=None,correlation_is_last=None)

Used to provide options for registering in autobahn.wamp.interfaces.ICallee.register().

Parameters

• match – Type of matching to use on the URI (exact, prefix or wildcard)

• invoke – Type of invoke mechanism to use (single, first, last, roundrobin, random)

• concurrency – if used, the number of times a particular endpoint may be called concur-rently (e.g. if this is 3, and there are already 3 calls in-progress a 4th call will receive anerror)

• details_arg (str) – When invoking the endpoint, provide call details in this keywordargument to the callable.

• details (bool) – When invoking the endpoint, provide call details in a keyword param-eter details.

• details_arg – DEPCREATED (use “details” flag). When invoking the endpoint, pro-vide call details in this keyword argument to the callable.

• force_reregister (bool) – if True, any other session that has already registered thisURI will be ‘kicked out’ and this session will become the one that’s registered (the previoussession must have used force_reregister=True as well)

• forward_for (list[dict]) – When this Register is forwarded over a router-to-routerlink, or via an intermediary router.

message_attr()Returns options dict as sent within WAMP messages.

class autobahn.wamp.types.CallDetails(registration, progress=None, caller=None,caller_authid=None, caller_authrole=None, pro-cedure=None, enc_algo=None, forward_for=None)

Provides details on a call when an endpoint previously registered is being called and opted to receive call details.

92 Chapter 9. API Reference

Page 101: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Parameters

• registration (instance of autobahn.wamp.request.Registration) – The(client side) registration object this invocation is delivered on.

• progress (callable or None) – A callable that will receive progressive call results.

• caller (int or None) – The WAMP session ID of the caller, if the latter is disclosed.Only filled when caller is disclosed.

• caller_authid (str or None) – The WAMP authid of the original caller of thisevent. Only filled when caller is disclosed.

• caller_authrole (str or None) – The WAMP authrole of the original caller ofthis event. Only filled when caller is disclosed.

• procedure (str or None) – For pattern-based registrations, the actual procedure URIbeing called.

• enc_algo (str or None) – Payload encryption algorithm that was in use (currently,either None or “cryptobox”).

• forward_for (list[dict]) – When this Call is forwarded for a client (or from anintermediary router).

class autobahn.wamp.types.CallOptions(on_progress=None, timeout=None, caller=None,caller_authid=None, caller_authrole=None, for-ward_for=None, correlation_id=None, corre-lation_uri=None, correlation_is_anchor=None,correlation_is_last=None, details=None)

Used to provide options for calling with autobahn.wamp.interfaces.ICaller.call().

Parameters

• on_progress (callable) – A callback that will be called when the remote endpointcalled yields interim call progress results.

• timeout (float) – Time in seconds after which the call should be automatically can-celed.

• forward_for (list[dict]) – When this Call is forwarded for a client (or from anintermediary router).

message_attr()Returns options dict as sent within WAMP messages.

class autobahn.wamp.types.CallResult(*results, **kwresults)Wrapper for remote procedure call results that contain multiple positional return values or keyword-based returnvalues.

Parameters

• results (list) – The positional result values.

• kwresults (dict) – The keyword result values.

class autobahn.wamp.types.EncodedPayload(payload, enc_algo, enc_serializer=None,enc_key=None)

Wrapper holding an encoded application payload when using WAMP payload transparency.

Parameters

• payload (bytes) – The encoded application payload.

• enc_algo (str) – The payload transparency algorithm identifier to check.

9.4. Module autobahn.wamp 93

Page 102: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• enc_serializer (str) – The payload transparency serializer identifier to check.

• enc_key (str or None) – If using payload transparency with an encryption algorithm,the payload encryption key.

9.4.3 WAMP Exceptions

exception autobahn.wamp.exception.ErrorBase class for all exceptions related to WAMP.

exception autobahn.wamp.exception.SessionNotReadyThe application tried to perform a WAMP interaction, but the session is not yet fully established.

exception autobahn.wamp.exception.SerializationErrorException raised when the WAMP serializer could not serialize the application payload (args or kwargs forCALL, PUBLISH, etc).

exception autobahn.wamp.exception.ProtocolErrorException raised when WAMP protocol was violated. Protocol errors are fatal and are handled by the WAMPimplementation. They are not supposed to be handled at the application level.

exception autobahn.wamp.exception.TransportLostException raised when the transport underlying the WAMP session was lost or is not connected.

exception autobahn.wamp.exception.ApplicationError(error, *args, **kwargs)Base class for all exceptions that can/may be handled at the application level.

Parameters error (str) – The URI of the error that occurred, e.g. wamp.error.not_authorized.

AUTHENTICATION_FAILED = u'wamp.error.authentication_failed'Something failed with the authentication itself, that is, authentication could not run to end.

AUTHORIZATION_FAILED = u'wamp.error.authorization_failed'A Dealer or Broker could not determine if the Peer is authorized to perform a join, call, register, publishor subscribe, since the authorization operation itself failed. E.g. a custom authorizer did run into an error.

CANCELED = u'wamp.error.canceled'A Dealer or Callee canceled a call previously issued (WAMP AP).

CLOSE_REALM = u'wamp.error.close_realm'The Peer want to leave the realm - used as a GOODBYE reason.

ENC_DECRYPT_ERROR = u'wamp.error.encryption.decrypt_error'WAMP-cryptobox application payload end-to-end encryption error.

ENC_NO_PAYLOAD_CODEC = u'wamp.error.no_payload_codec'WAMP message in payload transparency mode received, but no codec set or codec did not decode thepayload.

ENC_TRUSTED_URI_MISMATCH = u'wamp.error.encryption.trusted_uri_mismatch'WAMP-cryptobox application payload end-to-end encryption error.

GOODBYE_AND_OUT = u'wamp.error.goodbye_and_out'A Peer acknowledges ending of a session - used as a GOOBYE reply reason.

INVALID_ARGUMENT = u'wamp.error.invalid_argument'A call failed, since the given argument types or values are not acceptable to the called procedure - in whichcase the Callee may throw this error. Or a Router performing payload validation checked the payload(args / kwargs) of a call, call result, call error or publish, and the payload did not conform.

94 Chapter 9. API Reference

Page 103: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

INVALID_PAYLOAD = u'wamp.error.invalid_payload'The application payload could not be serialized.

INVALID_URI = u'wamp.error.invalid_uri'Peer provided an incorrect URI for a URI-based attribute of a WAMP message such as a realm, topic orprocedure.

NOT_AUTHORIZED = u'wamp.error.not_authorized'A call, register, publish or subscribe failed, since the session is not authorized to perform the operation.

NO_AUTH_METHOD = u'wamp.error.no_auth_method'No authentication method the peer offered is available or active.

NO_ELIGIBLE_CALLEE = u'wamp.error.no_eligible_callee'A Dealer could not perform a call, since a procedure with the given URI is registered, but Callee Black-and Whitelisting and/or Caller Exclusion lead to the exclusion of (any) Callee providing the procedure(WAMP AP).

NO_SUCH_PRINCIPAL = u'wamp.error.no_such_principal'A Peer was authenticated for an authid that does not or longer exists.

NO_SUCH_PROCEDURE = u'wamp.error.no_such_procedure'A Dealer could not perform a call, since not procedure is currently registered under the given URI.

NO_SUCH_REALM = u'wamp.error.no_such_realm'Peer wanted to join a non-existing realm (and the Router did not allow to auto-create the realm).

NO_SUCH_REGISTRATION = u'wamp.error.no_such_registration'A Dealer could not perform a unregister, since the given registration is not active.

NO_SUCH_ROLE = u'wamp.error.no_such_role'A Peer was to be authenticated under a Role that does not (or no longer) exists on the Router. For example,the Peer was successfully authenticated, but the Role configured does not exists - hence there is somemisconfiguration in the Router.

NO_SUCH_SESSION = u'wamp.error.no_such_session'A router could not perform an operation, since a session ID specified was non-existant.

NO_SUCH_SUBSCRIPTION = u'wamp.error.no_such_subscription'A Broker could not perform a unsubscribe, since the given subscription is not active.

PAYLOAD_SIZE_EXCEEDED = u'wamp.error.payload_size_exceeded'The application payload could not be transported becuase the serialized/framed payload exceeds the trans-port limits.

PROCEDURE_ALREADY_EXISTS = u'wamp.error.procedure_already_exists'A procedure could not be registered, since a procedure with the given URI is already registered.

PROCEDURE_EXISTS_INVOCATION_POLICY_CONFLICT = u'wamp.error.procedure_exists_with_different_invocation_policy'A procedure could not be registered, since a procedure with the given URI is already registered, and theregistration has a conflicting invocation policy.

SYSTEM_SHUTDOWN = u'wamp.error.system_shutdown'The Peer is shutting down completely - used as a GOODBYE (or ABORT) reason.

TIMEOUT = u'wamp.error.timeout'A pending (in-flight) call was timed out.

error_message()Get the error message of this exception.

Returns The error message.

9.4. Module autobahn.wamp 95

Page 104: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Return type str

exception autobahn.wamp.exception.NotAuthorizedNot authorized to perform the respective action.

exception autobahn.wamp.exception.InvalidUriThe URI for a topic, procedure or error is not a valid WAMP URI.

9.4.4 WAMP Authentication and Encryption

class autobahn.wamp.auth.AuthScram(**kw)Bases: object

Implements “wamp-scram” authentication for components.

NOTE: This is a prototype of a draft spec; see https://github.com/wamp-proto/wamp-proto/issues/135

on_welcome(session, authextra)When the server is satisfied, it sends a ‘WELCOME’ message.

This hook allows us an opportunity to deny the session right before it gets set up – we check the server-signature thus authorizing the server and if it fails we drop the connection.

autobahn.wamp.auth.pbkdf2(data, salt, iterations=1000, keylen=32, hashfunc=None)Returns a binary digest for the PBKDF2 hash algorithm of datawith the given salt. It iterates iterationstime and produces a key of keylen bytes. By default SHA-256 is used as hash function, a different hashlibhashfunc can be provided.

Parameters

• data (bytes) – The data for which to compute the PBKDF2 derived key.

• salt (bytes) – The salt to use for deriving the key.

• iterations (int) – The number of iterations to perform in PBKDF2.

• keylen (int) – The length of the cryptographic key to derive.

• hashfunc (str) – Name of the hash algorithm to use

Returns The derived cryptographic key.

Return type bytes

autobahn.wamp.auth.generate_totp_secret(length=10)Generates a new Base32 encoded, random secret.

See also:

http://en.wikipedia.org/wiki/Base32

Parameters length (int) – The length of the entropy used to generate the secret.

Returns The generated secret in Base32 (letters A-Z and digits 2-7). The length of the generatedsecret is length * 8 / 5 octets.

Return type unicode

autobahn.wamp.auth.compute_totp(secret, offset=0)Computes the current TOTP code.

Parameters

• secret (unicode) – Base32 encoded secret.

96 Chapter 9. API Reference

Page 105: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• offset (int) – Time offset (in steps, use eg -1, 0, +1 for compliance with RFC6238) forwhich to compute TOTP.

Returns TOTP for current time (+/- offset).

Return type unicode

autobahn.wamp.auth.derive_key(secret, salt, iterations=1000, keylen=32)Computes a derived cryptographic key from a password according to PBKDF2.

See also:

http://en.wikipedia.org/wiki/PBKDF2

Parameters

• secret (bytes or unicode) – The secret.

• salt (bytes or unicode) – The salt to be used.

• iterations (int) – Number of iterations of derivation algorithm to run.

• keylen (int) – Length of the key to derive in bytes.

Returns The derived key in Base64 encoding.

Return type bytes

autobahn.wamp.auth.generate_wcs(length=14)Generates a new random secret for use with WAMP-CRA.

The secret generated is a random character sequence drawn from

• upper and lower case latin letters

• digits

Parameters length (int) – The length of the secret to generate.

Returns The generated secret. The length of the generated is length octets.

Return type bytes

autobahn.wamp.auth.compute_wcs(key, challenge)Compute an WAMP-CRA authentication signature from an authentication challenge and a (derived) key.

Parameters

• key (bytes) – The key derived (via PBKDF2) from the secret.

• challenge (bytes) – The authentication challenge to sign.

Returns The authentication signature.

Return type bytes

class autobahn.wamp.cryptobox.EncodedPayload(payload, enc_algo, enc_serializer=None,enc_key=None)

Wrapper holding an encoded application payload when using WAMP payload transparency.

Parameters

• payload (bytes) – The encoded application payload.

• enc_algo (str) – The payload transparency algorithm identifier to check.

9.4. Module autobahn.wamp 97

Page 106: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• enc_serializer (str) – The payload transparency serializer identifier to check.

• enc_key (str or None) – If using payload transparency with an encryption algorithm,the payload encryption key.

9.5 Module autobahn.wamp.component

9.5.1 Component

This is common code for both Twisted and asyncio components; see either autobahn.twisted.component.Component or autobahn.asyncio.component.Component for the concrete implementations.

class autobahn.wamp.component.Component(main=None, transports=None, config=None,realm=u’realm1’, extra=None, authen-tication=None, session_factory=None,is_fatal=None)

A WAMP application component. A component holds configuration for (and knows how to create) transportsand sessions.

Parameters

• main (callable taking 2 args: reactor, ISession) – After a transporthas been connected and a session has been established and joined to a realm, this (async)procedure will be run until it finishes – which signals that the component has run to com-pletion. In this case, it usually doesn’t make sense to use the on_* kwargs. If you do notpass a main() procedure, the session will not be closed (unless you arrange for .leave() to becalled).

• transports (None or unicode or list of dicts) – Transport configura-tions for creating transports. Each transport can be a WAMP URL, or a dict containingthe following configuration keys:

– type (optional): websocket (default) or rawsocket

– url: the router URL

– endpoint (optional, derived from URL if not provided):

* type: “tcp” or “unix”

* host, port: only for TCP

* path: only for unix

* timeout: in seconds

* tls: True or (under Twisted) an twisted.internet.ssl.IOpenSSLClientComponentCreator instance (such as returnedfrom twisted.internet.ssl.optionsForClientTLS) orCertificateOptions instance.

• realm (unicode) – the realm to join

• authentication (dict mapping auth_type to dict) – configuration of au-thenticators

• session_factory (callable) – if None, ApplicationSession is used, other-wise a callable taking a single config argument that is used to create a new ApplicationS-ession instance.

98 Chapter 9. API Reference

Page 107: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• is_fatal (callable taking one arg, or None) – a callable taking a singleargument, an Exception instance. The callable should return True if this error is “fatal”,meaning we should not try connecting to the current transport again. The default behavior(on None) is to always return False

on_connect(fn)A decorator as a shortcut for listening for ‘connect’ events.

on_connectfailure(fn)A decorator as a shortcut for listening for ‘connectfailure’ events.

on_disconnect(fn)A decorator as a shortcut for listening for ‘disconnect’ events.

on_join(fn)A decorator as a shortcut for listening for ‘join’ events.

For example:

@component.on_joindef joined(session, details):

print("Session {} joined: {}".format(session, details))

on_leave(fn)A decorator as a shortcut for listening for ‘leave’ events.

on_ready(fn)A decorator as a shortcut for listening for ‘ready’ events.

register(uri, options=None)A decorator as a shortcut for registering during on-join

For example:

@component.register(u"com.example.add",options=RegisterOptions(invoke='round_robin'),

)def add(*args, **kw):

print("add({}, {}): event received".format(args, kw))

session_factory = NoneThe factory of the session we will instantiate.

subscribe(topic, options=None)A decorator as a shortcut for subscribing during on-join

For example:

@component.subscribe(u"some.topic",options=SubscribeOptions(match=u'prefix'),

)def topic(*args, **kw):

print("some.topic({}, {}): event received".format(args, kw))

9.6 Module autobahn.twisted

Autobahn Twisted specific classes. These are used when Twisted is run as the underlying networking framework.

9.6. Module autobahn.twisted 99

Page 108: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

9.6.1 Component

The component API provides a high-level funcional style method of defining and running WAMP components includ-ing authentication configuration

class autobahn.twisted.component.Component(main=None, transports=None, config=None,realm=u’realm1’, extra=None, authen-tication=None, session_factory=None,is_fatal=None)

A component establishes a transport and attached a session to a realm using the transport for communication.

The transports a component tries to use can be configured, as well as the auto-reconnect strategy.

Parameters

• main (callable taking 2 args: reactor, ISession) – After a trans-port has been connected and a session has been established and joined to a realm, this(async) procedure will be run until it finishes – which signals that the component has runto completion. In this case, it usually doesn’t make sense to use the on_* kwargs. Ifyou do not pass a main() procedure, the session will not be closed (unless you arrange for.leave() to be called).

• transports (None or unicode or list of dicts) – Transport configura-tions for creating transports. Each transport can be a WAMP URL, or a dict containingthe following configuration keys:

– type (optional): websocket (default) or rawsocket

– url: the router URL

– endpoint (optional, derived from URL if not provided):

* type: “tcp” or “unix”

* host, port: only for TCP

* path: only for unix

* timeout: in seconds

* tls: True or (under Twisted) an twisted.internet.ssl.IOpenSSLClientComponentCreator instance (such as returnedfrom twisted.internet.ssl.optionsForClientTLS) orCertificateOptions instance.

• realm (unicode) – the realm to join

• authentication (dict mapping auth_type to dict) – configuration ofauthenticators

• session_factory (callable) – if None, ApplicationSession is used, oth-erwise a callable taking a single config argument that is used to create a new Applica-tionSession instance.

• is_fatal (callable taking one arg, or None) – a callable taking a sin-gle argument, an Exception instance. The callable should return True if this error is“fatal”, meaning we should not try connecting to the current transport again. The defaultbehavior (on None) is to always return False

session_factoryalias of autobahn.twisted.wamp.Session

100 Chapter 9. API Reference

Page 109: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

start(reactor=None)This starts the Component, which means it will start connecting (and re-connecting) to its configuredtransports. A Component runs until it is “done”, which means one of: - There was a “main” functiondefined, and it completed successfully; - Something called .leave() on our session, and we left suc-cessfully; - .stop() was called, and completed successfully; - none of our transports were able toconnect successfully (failure); :returns: a Deferred that fires (with None) when we are

“done” or with a Failure if something went wrong.

autobahn.twisted.component.run(components, log_level=’info’)High-level API to run a series of components.

This will only return once all the components have stopped (including, possibly, after all re-connections havefailed if you have re-connections enabled). Under the hood, this calls twisted.internet.reactor.run() – if you wish to manage the reactor loop yourself, use the autobahn.twisted.component.Component.start() method to start each component yourself.

Parameters

• components (Component or list of Components) – the Component(s) youwish to run

• log_level (string) – a valid log-level (or None to avoid calling start_logging)

9.6.2 WebSocket Protocols and Factories

Classes for WebSocket clients and servers using Twisted.

class autobahn.twisted.websocket.WebSocketServerProtocolBase class for Twisted-based WebSocket server protocols.

Implements autobahn.websocket.interfaces.IWebSocketChannel.

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.twisted.websocket.WebSocketClientProtocolBase class for Twisted-based WebSocket client protocols.

Implements autobahn.websocket.interfaces.IWebSocketChannel.

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.twisted.websocket.WebSocketServerFactory(*args, **kwargs)Base class for Twisted-based WebSocket server factories.

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory

Note: In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketServerChannelFactory(), you can supply a reactor keyword argument to specify theTwisted reactor to be used.

class autobahn.twisted.websocket.WebSocketClientFactory(*args, **kwargs)Base class for Twisted-based WebSocket client factories.

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory

9.6. Module autobahn.twisted 101

Page 110: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Note: In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketClientChannelFactory(), you can supply a reactor keyword argument to specify theTwisted reactor to be used.

9.6.3 WAMP-over-WebSocket Protocols and Factories

Classes for WAMP-WebSocket clients and servers using Twisted.

class autobahn.twisted.websocket.WampWebSocketServerProtocolTwisted-based WAMP-over-WebSocket server protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

class autobahn.twisted.websocket.WampWebSocketClientProtocolTwisted-based WAMP-over-WebSocket client protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

class autobahn.twisted.websocket.WampWebSocketServerFactory(factory, *args,**kwargs)

Twisted-based WAMP-over-WebSocket server protocol factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializers (list of objects implementing autobahn.wamp.interfaces.ISerializer) – A list of WAMP serializers to use (or None for all available seri-alizers).

protocolalias of WampWebSocketServerProtocol

class autobahn.twisted.websocket.WampWebSocketClientFactory(factory, *args,**kwargs)

Twisted-based WAMP-over-WebSocket client protocol factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializer (object implementing autobahn.wamp.interfaces.ISerializer) – The WAMP serializer to use (or None for “best” serializer,chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON,JSON).

protocolalias of WampWebSocketClientProtocol

9.6.4 WAMP-over-RawSocket Protocols and Factories

Classes for WAMP-RawSocket clients and servers using Twisted.

102 Chapter 9. API Reference

Page 111: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.twisted.rawsocket.WampRawSocketServerProtocolTwisted-based WAMP-over-RawSocket server protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.twisted.rawsocket.WampRawSocketClientProtocolTwisted-based WAMP-over-RawSocket client protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.twisted.rawsocket.WampRawSocketServerFactory(factory, serializ-ers=None)

Twisted-based WAMP-over-RawSocket server protocol factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializers (list of objects implementing autobahn.wamp.interfaces.ISerializer) – A list of WAMP serializers to use (or None for all available seri-alizers).

protocolalias of WampRawSocketServerProtocol

class autobahn.twisted.rawsocket.WampRawSocketClientFactory(factory, serial-izer=None)

Twisted-based WAMP-over-RawSocket client protocol factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializer (object implementing autobahn.wamp.interfaces.ISerializer) – The WAMP serializer to use (or None for “best” serializer,chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON,JSON).

protocolalias of WampRawSocketClientProtocol

9.6.5 WAMP Sessions

Classes for WAMP sessions using Twisted.

class autobahn.twisted.wamp.ApplicationSession(config=None)WAMP application session for Twisted-based applications.

Implements:

• autobahn.wamp.interfaces.ITransportHandler

9.6. Module autobahn.twisted 103

Page 112: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• autobahn.wamp.interfaces.ISession

Implements autobahn.wamp.interfaces.ISession()

class autobahn.twisted.wamp.ApplicationRunner(url, realm=None, extra=None, serial-izers=None, ssl=None, proxy=None,headers=None, max_retries=None,initial_retry_delay=None,max_retry_delay=None,retry_delay_growth=None,retry_delay_jitter=None)

This class is a convenience tool mainly for development and quick hosting of WAMP application components.

It can host a WAMP application component in a WAMP-over-WebSocket client connecting to a WAMP router.

Parameters

• url (str) – The WebSocket URL of the WAMP router to connect to (e.g.ws://somehost.com:8090/somepath)

• realm (str) – The WAMP realm to join the application session to.

• extra (dict) – Optional extra configuration to forward to the application component.

• serializers (list) – A list of WAMP serializers to use (or None for default serializ-ers). Serializers must implement autobahn.wamp.interfaces.ISerializer.

• ssl (twisted.internet.ssl.CertificateOptions) – (Optional). Ifspecified this should be an instance suitable to pass as sslContextFactoryto twisted.internet.endpoints.SSL4ClientEndpoint` such astwisted.internet.ssl.CertificateOptions. Leaving it as None willuse the result of calling Twisted’s twisted.internet.ssl.platformTrust()which tries to use your distribution’s CA certificates.

• proxy (dict or None) – Explicit proxy server to use; a dict with host and portkeys

• headers (dict) – Additional headers to send (only applies to WAMP-over-WebSocket).

• max_retries (int) – Maximum number of reconnection attempts. Unlimited if setto -1.

• initial_retry_delay (float) – Initial delay for reconnection attempt in seconds(Default: 1.0s).

• max_retry_delay (float) – Maximum delay for reconnection attempts in seconds(Default: 60s).

• retry_delay_growth (float) – The growth factor applied to the retry delay be-tween reconnection attempts (Default 1.5).

• retry_delay_jitter (float) – A 0-argument callable that introduces nose intothe delay. (Default random.random)

run(make, start_reactor=True, auto_reconnect=False, log_level=’info’, endpoint=None, reac-tor=None)Run the application component.

Parameters

• make (callable) – A factory that produces instances of autobahn.twisted.wamp.ApplicationSession when called with an instance of autobahn.wamp.types.ComponentConfig.

104 Chapter 9. API Reference

Page 113: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• start_reactor – When True (the default) this method starts the Twisted reactorand doesn’t return until the reactor stops. If there are any problems starting the reactoror connect()-ing, we stop the reactor and raise the exception back to the caller.

Returns None is returned, unless you specify start_reactor=False in which case theDeferred that connect() returns is returned; this will callback() with an IProtocol instance,which will actually be an instance of WampWebSocketClientProtocol

stop()Stop reconnecting, if auto-reconnecting was enabled.

9.7 Module autobahn.asyncio

Autobahn asyncio specific classes. These are used when asyncio is run as the underlying networking framework.

9.7.1 Component

The component API provides a high-level funcional style method of defining and running WAMP components includ-ing authentication configuration

class autobahn.asyncio.component.Component(main=None, transports=None, config=None,realm=u’realm1’, extra=None, authen-tication=None, session_factory=None,is_fatal=None)

A component establishes a transport and attached a session to a realm using the transport for communication.

The transports a component tries to use can be configured, as well as the auto-reconnect strategy.

Parameters

• main (callable taking 2 args: reactor, ISession) – After a trans-port has been connected and a session has been established and joined to a realm, this(async) procedure will be run until it finishes – which signals that the component has runto completion. In this case, it usually doesn’t make sense to use the on_* kwargs. Ifyou do not pass a main() procedure, the session will not be closed (unless you arrange for.leave() to be called).

• transports (None or unicode or list of dicts) – Transport configura-tions for creating transports. Each transport can be a WAMP URL, or a dict containingthe following configuration keys:

– type (optional): websocket (default) or rawsocket

– url: the router URL

– endpoint (optional, derived from URL if not provided):

* type: “tcp” or “unix”

* host, port: only for TCP

* path: only for unix

* timeout: in seconds

* tls: True or (under Twisted) an twisted.internet.ssl.IOpenSSLClientComponentCreator instance (such as returnedfrom twisted.internet.ssl.optionsForClientTLS) orCertificateOptions instance.

9.7. Module autobahn.asyncio 105

Page 114: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• realm (unicode) – the realm to join

• authentication (dict mapping auth_type to dict) – configuration ofauthenticators

• session_factory (callable) – if None, ApplicationSession is used, oth-erwise a callable taking a single config argument that is used to create a new Applica-tionSession instance.

• is_fatal (callable taking one arg, or None) – a callable taking a sin-gle argument, an Exception instance. The callable should return True if this error is“fatal”, meaning we should not try connecting to the current transport again. The defaultbehavior (on None) is to always return False

session_factoryalias of autobahn.asyncio.wamp.Session

start(loop=None)This starts the Component, which means it will start connecting (and re-connecting) to its configuredtransports. A Component runs until it is “done”, which means one of: - There was a “main” functiondefined, and it completed successfully; - Something called .leave() on our session, and we left suc-cessfully; - .stop() was called, and completed successfully; - none of our transports were able toconnect successfully (failure); :returns: a Future which will resolve (to None) when we are

“done” or with an error if something went wrong.

autobahn.asyncio.component.run(components, log_level=’info’)High-level API to run a series of components.

This will only return once all the components have stopped (including, possibly, after all re-connections havefailed if you have re-connections enabled). Under the hood, this calls

XXX fixme for asyncio

– if you wish to manage the loop yourself, use the autobahn.asyncio.component.Component.start() method to start each component yourself.

Parameters

• components (Component or list of Components) – the Component(s) youwish to run

• log_level (string) – a valid log-level (or None to avoid calling start_logging)

9.7.2 WebSocket Protocols and Factories

Classes for WebSocket clients and servers using asyncio.

class autobahn.asyncio.websocket.WebSocketServerProtocolBase class for asyncio-based WebSocket server protocols.

Implements:

• autobahn.websocket.interfaces.IWebSocketChannel

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.asyncio.websocket.WebSocketClientProtocolBase class for asyncio-based WebSocket client protocols.

Implements:

106 Chapter 9. API Reference

Page 115: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• autobahn.websocket.interfaces.IWebSocketChannel

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.asyncio.websocket.WebSocketServerFactory(*args, **kwargs)Base class for asyncio-based WebSocket server factories.

Implements:

• autobahn.websocket.interfaces.IWebSocketServerChannelFactory

Note: In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketServerChannelFactory(), you can supply a loop keyword argument to specify the asyn-cio event loop to be used.

protocolalias of WebSocketServerProtocol

class autobahn.asyncio.websocket.WebSocketClientFactory(*args, **kwargs)Base class for asyncio-based WebSocket client factories.

Implements:

• autobahn.websocket.interfaces.IWebSocketClientChannelFactory

Note: In addition to all arguments to the constructor of autobahn.websocket.interfaces.IWebSocketClientChannelFactory(), you can supply a loop keyword argument to specify the asyn-cio event loop to be used.

9.7.3 WAMP-over-WebSocket Protocols and Factories

Classes for WAMP-WebSocket clients and servers using asyncio.

class autobahn.asyncio.websocket.WampWebSocketServerProtocolasyncio-based WAMP-over-WebSocket server protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

class autobahn.asyncio.websocket.WampWebSocketClientProtocolasyncio-based WAMP-over-WebSocket client protocols.

Implements:

• autobahn.wamp.interfaces.ITransport

class autobahn.asyncio.websocket.WampWebSocketServerFactory(factory, *args,**kwargs)

asyncio-based WAMP-over-WebSocket server factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

9.7. Module autobahn.asyncio 107

Page 116: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• serializers (list of objects implementing autobahn.wamp.interfaces.ISerializer) – A list of WAMP serializers to use (or None for all available seri-alizers).

protocolalias of WampWebSocketServerProtocol

class autobahn.asyncio.websocket.WampWebSocketClientFactory(factory, *args,**kwargs)

asyncio-based WAMP-over-WebSocket client factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializer (object implementing autobahn.wamp.interfaces.ISerializer) – The WAMP serializer to use (or None for “best” serializer,chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON,JSON).

protocolalias of WampWebSocketClientProtocol

9.7.4 WAMP-over-RawSocket Protocols and Factories

Classes for WAMP-RawSocket clients and servers using asyncio.

class autobahn.asyncio.rawsocket.WampRawSocketServerProtocolasyncio-based WAMP-over-RawSocket server protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.asyncio.rawsocket.WampRawSocketClientProtocolasyncio-based WAMP-over-RawSocket client protocol.

Implements:

• autobahn.wamp.interfaces.ITransport

get_channel_id(channel_id_type=u’tls-unique’)Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

class autobahn.asyncio.rawsocket.WampRawSocketServerFactory(factory, serializ-ers=None)

asyncio-based WAMP-over-RawSocket server protocol factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializers (list of objects implementing autobahn.wamp.interfaces.ISerializer) – A list of WAMP serializers to use (or None for all available seri-alizers).

protocolalias of WampRawSocketServerProtocol

108 Chapter 9. API Reference

Page 117: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

class autobahn.asyncio.rawsocket.WampRawSocketClientFactory(factory, serial-izer=None)

asyncio-based WAMP-over-RawSocket client factory.

Parameters

• factory (callable) – A callable that produces instances that implementautobahn.wamp.interfaces.ITransportHandler

• serializer (object implementing autobahn.wamp.interfaces.ISerializer) – The WAMP serializer to use (or None for “best” serializer,chosen as the first serializer available from this list: CBOR, MessagePack, UBJSON,JSON).

protocolalias of WampRawSocketClientProtocol

9.7.5 WAMP Sessions

Classes for WAMP sessions using asyncio.

class autobahn.asyncio.wamp.ApplicationSession(config=None)WAMP application session for asyncio-based applications.

Implements:

• autobahn.wamp.interfaces.ITransportHandler

• autobahn.wamp.interfaces.ISession

Implements autobahn.wamp.interfaces.ISession()

class autobahn.asyncio.wamp.ApplicationRunner(url, realm=None, extra=None, serializ-ers=None, ssl=None, proxy=None, head-ers=None)

This class is a convenience tool mainly for development and quick hosting of WAMP application components.

It can host a WAMP application component in a WAMP-over-WebSocket client connecting to a WAMP router.

Parameters

• url (str) – The WebSocket URL of the WAMP router to connect to (e.g.ws://somehost.com:8090/somepath)

• realm (str) – The WAMP realm to join the application session to.

• extra (dict) – Optional extra configuration to forward to the application component.

• serializers (list) – A list of WAMP serializers to use (or None for default serializ-ers). Serializers must implement autobahn.wamp.interfaces.ISerializer.

• ssl (ssl.SSLContext or bool) – An (optional) SSL context instance or a bool. Seethe documentation for the loop.create_connection asyncio method, to which this value ispassed as the ssl keyword parameter.

• proxy (dict or None) – Explicit proxy server to use; a dict with host and portkeys

• headers (dict) – Additional headers to send (only applies to WAMP-over-WebSocket).

run(make, start_loop=True, log_level=’info’)Run the application component. Under the hood, this runs the event loop (unless start_loop=False ispassed) so won’t return until the program is done.

9.7. Module autobahn.asyncio 109

Page 118: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

Parameters

• make (callable) – A factory that produces instances of autobahn.asyncio.wamp.ApplicationSession when called with an instance of autobahn.wamp.types.ComponentConfig.

• start_loop (bool) – When True (the default) this method start a new asyncioloop.

Returns None is returned, unless you specify start_loop=False in which case the coroutinefrom calling loop.create_connection() is returned. This will yield the (transport, protocol)pair.

stop()Stop reconnecting, if auto-reconnecting was enabled.

110 Chapter 9. API Reference

Page 119: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

CHAPTER 10

Changelog

10.1 19.10.1

• new: updated docker image scripts

• new: add WAMP serializer in use to SessionDetails

• fix: partial support for xb buyers/sellers in pypy

• fix: remove dependency on “ethereum” package (part of pypy support)

10.2 19.9.3

• new: XBR - update XBR for new contract ABIs

• new: XBR - payment channel close

• new: XBR - implement EIP712 signing of messages in endpoints

10.3 19.9.2

• new: XBR - update XBR for new contract ABIs

10.4 19.9.1

• new: XBR - update XBR for new contract ABIs

111

Page 120: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.5 19.8.1

• new: implement XBR off-chain delegate transaction signing and verification (#1202)

• new: update XBR for new contract ABIs

10.6 19.7.2

• fix: monkey patch re-add removed helper functions removed in eth-abi

• new: simple blockchain (XBR) client

• new: update XBR ABI files

• new: XBR endpoint transaction signing

• new: client side catching of WAMP URI errors in session.call|register|publish|subscribe

10.7 19.7.1

• fix: implement client side payload exceed max size; improve max size exceeded handling

• fix: detect when our transport is “already” closed at connect time (#1215)

• fix: XBR examples

10.8 19.6.2

• fix: add forgotten cryptography dependency (#1205)

10.9 19.6.1

• new: XBR client library integrated (#1201)

• new: add entropy depletion unit tests

• fix: make CLI tool python2 compatible (#1197)

• fix: use cryptography pbkdf2 instead of custom (#1198)

• fix: include tests for packaging (#1194)

10.10 19.5.1

• fix: authextra merging (#1191)

• fix: set default retry_delay_jitter (#1190)

• new: add rawsocket + twisted example (#1189)

• new: WebSocket testing support, via Agent-style interface (#1186)

112 Chapter 10. Changelog

Page 121: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• new: decorator for on_connectfailure

• fix: delayed call leakage (#1152)

• new: CLI client (#1150)

• fix: set up TLS over proxy properly (#1149)

• new: expose ser modules (#1148)

• fix: base64 encodings, add hex encoding (#1146)

• new: onConnecting callback (with TransportDetails and ConnectingRequest). Note: if you’ve implemented apure IWebSocketChannel without inheriting from Autobahn base classes, you’ll need to add an onConnecting()method that just does return None.

10.11 19.3.3

• fix: RegisterOptions should have details|bool parameter (#1143)

• new: WAMP callee disclosure

• new: WAMP forward_for in more message types; expose forward_for in options/details types

• new: expose underlying serializer modules on WAMP object serializers

• fix: WAMP-cryptosign fix base64 encodings, add hex encoding (#1146)

10.12 19.3.2

• fix: import guards for flatbuffers (missed in CI as we run with “all deps installed” there)

10.13 19.3.1

• new: add experimental support for WAMP-FlatBuffers serializer: EVENT and PUBLISH messages for nowonly

• new: add FlatBuffers schema for WAMP messages

• fix: improve serializer package preference behavior depending on CPy vs PyPy

• fix: relax protocol violations: ignore unknown INTERRUPT and GOODBYE already sent; reduce log noise

• fix: skipping Yield message if transport gets closed before success callback is called (#1119)

• fix: integer division in logging in py3 (#1120)

• fix: Await tasks after they’ve been cancelled in autobahn.asycio.component.nicely_exit (#1116)

10.14 19.2.1

• fix: set announced roles on appsession object (#1109)

• new: lower log noise on ApplicationErrors (#1107)

• new: allow explicit passing of tx endpoint and reactor (#1103)

10.11. 19.3.3 113

Page 122: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• new: add attribute to forward applicationrunner to applicationsession via componentconfig

10.15 19.1.1

• new: adding marshal on SessionDetails

10.16 18.12.1

• fix: return the wrapped function from component decorators (#1093)

• new: add proxy= support for Component transports (#1091)

• fix: Ticket1077 stop start (#1090)

• fix: cleanup cancel handling (#1087)

10.17 18.11.2

• fix: asyncio unregisterProducer raises exception (#1079)

• fix: URL is not required in RawSocket configuration items with WAMP component API

• fix: revert PR https://github.com/crossbario/autobahn-python/pull/1075

10.18 18.11.1

• new: forward_for WAMP message attribute (for Crossbar.io Router-to-Router federation)

• new: support RawSocket URLs (eg “rs://localhost:5000” or “rs://unix:/tmp/file.sock”)

• new: support WAMP-over-Unix sockets for WAMP components (“new API”)

• fix: use same WAMP serializer construction code for WAMP components (“new API”) and ApplicationSes-sion/Runner

• fix: memory leak with Twisted/WebSocket, dropConnection and producer

10.19 18.10.1

• Don’t eat Component.stop() request when crossbar not connected (#1066)

• handle async on_progress callbacks properly (#1061)

• fix attribute error when ConnectionResetError does not contain “reason” attribute (#1059)

• infer rawsocket host, port from URL (#1056)

• fix error on connection lost if no reason (reason = None) (#1055)

• fixed typo on class name (#1054)

114 Chapter 10. Changelog

Page 123: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.20 18.9.2

• fix: TLS error logging (#1052)

10.21 18.9.1

• new: Interrupt has Options.reason to signal detailed origin of call cancelation (active cancel vs passive timeout)

• fix: Cancel and Interrupt gets "killnowait" mode

• new: Cancel and Interrupt no longer have ABORT/"abort"

10.22 18.8.2

• new: WAMP call cancel support

• fix: getting started documentation and general docs improvements

• fix: WebSocket auto-reconnect on opening handshake failure

• fix: more Python 3.7 compatibility and CI

• fix: Docker image building using multi-arch, size optimizations and more

• fix: asyncio failed to re-connect under some circumstances (#1040, #1041, #1010, #1030)

10.23 18.8.1

• fix: Python 3.7 compatibility

• fix: remove Python 2.6 support leftovers

• new: getting started docker-based examples in matching with docs

10.24 18.7.1

• new: Python 3.7 supported and integrated into CI

• new: WAMP-SCRAM examples

• fix: glitches in WAMP-SCRAM

10.25 18.6.1

• fix: implement abort argument for asyncio in WebSocketAdapterProtocol._closeConnection (#1012)

10.20. 18.9.2 115

Page 124: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.26 18.5.2

• fix: security (DoS amplification): a WebSocket server with permessage-deflate turned on could be induced towaste extra memory through a “zip-bomb” style attack. Setting a max-message-size will now stop deflatingcompressed data when the max is reached (instead of consuming all compressed data first). This could be usedby a malicious client to make the server waste much more memory than the bandwidth the client uses.

10.27 18.5.1

• fix: asyncio/rawsocket buffer processing

• fix: example failures due to pypy longer startup time (#996)

• fix: add on_welcome for AuthWampCra (#992)

• fix: make run() of multiple components work on Windows (#986)

• new: max_retries now defaults to -1 (“try forever”)

10.28 18.4.1

• new: WAMP-SCRAM authentication

• new: native vector extensions (NVX)

• fix: improve choosereactor (#965, #963)

• new: lots of new and improved documentation, component API and more

• new: Docker image tooling now in this repo

• fix: “fatal errors” in Component (#977)

• fix: AIO/Component: create a new loop if already closed

• fix: kwarg keys sometimes are bytes on Python2 (#980)

• fix: various improvements to new component API

10.29 18.3.1

• fix: endpoint configuration error messages (#942)

• fix: various improvements to the new components API (including retries)

• fix: pass unregisterProducer through to twisted to complement WebSocketAdapterProtocol.registerProducer(#875)

10.30 17.10.1

• fix: proxy support (#918)

• fix: ensure that a future is not done before rejecting it (#919)

• fix: don’t try to reject cancelled futures within pending requests when closing the session

116 Chapter 10. Changelog

Page 125: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.31 17.9.3

Published 2017-09-23

• new: user configurable backoff policy

• fix: close aio loop on exit

• fix: some component API cleanups

• fix: cryptosign on py2

• new: allow setting correlation_is_last message marker in WAMP messages from user code

10.32 17.9.2

Published 2017-09-12

• new: allow setting correlation URI and anchor flag in WAMP messages from user code

• fix: WebSocket proxy connect on Python 3 (unicode vs bytes bug)

10.33 17.9.1

Published 2017-09-04

• new: allow setting correlation ID in WAMP messages from user code

• fix: distribute LICENSE file in all distribution formats (using setup.cfg metadata)

10.34 17.8.1

Published 2017-08-15

• new: prefix= kwarg now available on ApplicationSession.register for runtime method names

• new: @wamp.register(None) will use the function-name as the URI

• new: correlation and uri attributes for WAMP message tracing

10.35 17.7.1

Published 2017-07-21

• new: lots of improvements of components API, including asyncio support

10.36 17.6.2

Published 2017-06-24

• new: force register option when joining realms

• fix: TLS options in components API

10.31. 17.9.3 117

Page 126: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.37 17.6.1

Published 2017-06-07

• new: allow components to pass WebSocket/RawSocket options

• fix: register/subscribe decorators support different URI syntax from what session.register and session.subscribesupport

• new: allow for standard Crossbar a.c..d style pattern URIs to be used with Pattern

• new: dynamic authorizer example

• new: configurable log level in ApplicationRunner.run for asyncio

• fix: forward reason of hard dropping WebSocket connection in wasNotCleanReason

10.38 17.5.1

Published 2017-05-01

• new: switched to calendar-based release/version numbering

• new: WAMP event retention example and docs

• new: WAMP subscribe/register options on WAMP decorators

• fix: require all TLS dependencies on extra_require_encryption setuptools

• new: support for X-Forwarded-For HTTP header

• fix: ABC interface definitions where missing “self”

10.39 0.18.2

Published 2017-04-14

• new: payload codec API

• fix: make WAMP-cryptobox use new payload codec API

• fix: automatic binary conversation for JSON

• new: improvements to experimental component API

10.40 0.18.1

Published 2017-03-28

• fix: errback all user handlers for all WAMP requests still outstanding when session/transport is closed/lost

• fix: allow WebSocketServerProtocol.onConnect to return a Future/Deferred

• new: allow configuration of RawSocket serializer

• new: test all examples on both WebSocket and RawSocket

• fix: revert to default arg for Deny reason

118 Chapter 10. Changelog

Page 127: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• new: WAMP-RawSocket and WebSocket default settings for asyncio

• new: experimental component based API and new WAMP Session class

10.41 0.18.0

Published 2017-03-26

• fix: big docs cleanup and polish

• fix: docs for publisher black-/whitelisting based on authid/authrole

• fix: serialization for publisher black-/whitelisting based on authid/authrole

• new: allow to stop auto-reconnecting for Twisted ApplicationRunner

• fix: allow empty realms (router decides) for asyncio ApplicationRunner

10.42 0.17.2

Published 2017-02-25

• new: WAMP-cryptosign elliptic curve based authentication support for asyncio

• new: CI testing on Twisted 17.1

• new: controller/shared attributes on ComponentConfig

10.43 0.17.1

Published 2016-12-29

• new: demo MQTT and WAMP clients interoperating via Crossbar.io

• new: WAMP message attributes for message resumption

• new: improvements to experimental WAMP components API

• fix: Python 3.4.4+ when using asyncio

10.44 0.17.0

Published 2016-11-30

• new: WAMP PubSub event retention

• new: WAMP PubSub last will / testament

• new: WAMP PubSub acknowledged delivery

• fix: WAMP Session lifecycle - properly handle asynchronous ApplicationSession.onConnect for asyncio

10.41. 0.18.0 119

Page 128: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.45 0.16.1

Published 2016-11-07

• fix: inconsistency between PublishOptions and Publish message

• new: improve logging with dropped connections (eg due to timeouts)

• fix: various smaller asyncio fixes

• new: rewrite all examples for new Python 3.5 async/await syntax

• fix: copyrights transferred from Tavendo GmbH to Crossbar.io Technologies GmbH

10.46 0.16.0

Published 2016-08-14

• new: new autobahn.wamp.component API in experimental stage

• new: Ed25519 OpenSSH and OpenBSD signify key support

• fix: allow Py2 and async user code in onConnect callback of asyncio

10.47 0.15.0

Published 2016-07-19

• new: WAMP AP option: register with maximum concurrency

• new: automatic reconnect for WAMP clients ApplicationRunner on Twisted

• new: RawSocket support in WAMP clients using ApplicationRunner on Twisted

• new: Set WebSocket production settings on WAMP clients using ApplicationRunner on Twisted

• fix: #715 Py2/Py3 issue with WebSocket traffic logging

• new: allow WAMP factories to take classes OR instances of ApplicationSession

• fix: make WebSocketResource working on Twisted 16.3

• fix: remove some minified AutobahnJS from examples (makes distro packagers happy)

• new: WAMP-RawSocket transport for asyncio

• fix: #691 (security) If the allowedOrigins websocket option was set, the resulting matching was insufficient andwould allow more origins than intended

10.48 0.14.1

Published 2016-05-26

• fix: unpinned Twisted version again

• fix: remove X-Powered-By header

• fix: removed decrecated args to ApplicationRunner

120 Chapter 10. Changelog

Page 129: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.49 0.14.0

Published 2016-05-01

• new: use of batched/chunked timers to massively reduce CPU load with WebSocket auto-ping/pong

• new: support new UBJSON WAMP serialization format

• new: publish universal wheels

• fix: replaced msgpack-python with u-msgpack-python

• fix: some glitches with eligible / exlude when used with authid / authrole

• fix: some logging glitches

• fix: pin Twisted at 16.1.1 (for now)

10.50 0.13.1

Published 2016-04-09

• moved helper funs for WebSocket URL handling to autobahn.websocket.util

• fix: marshal WAMP options only when needed

• fix: various smallish examples fixes

10.51 0.13.0

Published 2016-03-15

• fix: better traceback logging (#613)

• fix: unicode handling in debug messages (#606)

• fix: return Deferred from run() (#603).

• fix: more debug logging improvements

• fix: more Pattern tests, fix edge case (#592).

• fix: better logging from asyncio ApplicationRunner

• new: disclose becomes a strict router-side feature (#586).

• new: subscriber black/whitelisting using authid/authrole

• new: asyncio websocket testee

• new: refine Observable API (#593).

10.52 0.12.1

Published 2016-01-30

• new: support CBOR serialization in WAMP

• new: support WAMP payload transparency

10.49. 0.14.0 121

Page 130: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• new: beta version of WAMP-cryptosign authentication method

• new: alpha version of WAMP-cryptobox end-to-end encryption

• new: support user provided authextra data in WAMP authentication

• new: support WAMP channel binding

• new: WAMP authentication util functions for TOTP

• fix: support skewed time leniency for TOTP

• fix: use the new logging system in WAMP implementation

• fix: some remaining Python 3 issues

• fix: allow WAMP prefix matching register/subscribe with dot at end of URI

10.53 0.11.0

Published 2015-12-09

10.54 0.10.9

Published 2015-09-15

• fixes regression #500 introduced with commit 9f68749

10.55 0.10.8

Published 2015-09-13

• maintenance release with some issues fixed

10.56 0.10.7

Published 2015-09-06

• fixes a regression in 0.10.6

10.57 0.10.6

Published 2015-09-05

• maintenance release with nearly two dozen fixes

• improved Python 3, error logging, WAMP connection mgmt, ..

122 Chapter 10. Changelog

Page 131: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.58 0.10.5

Published 2015-08-06

• maintenance release with lots of smaller bug fixes

10.59 0.10.4

Published 2015-05-08

• maintenance release with some smaller bug fixes

10.60 0.10.3

Published 2015-04-14

• new: using txaio package

• new: revised WAMP-over-RawSocket specification implemented

• fix: ignore unknown attributes in WAMP Options/Details

10.61 0.10.2

Published 2015-03-19

• fix: Twisted 11 lacks IPv6 address class

• new: various improvements handling errors from user code

• new: add parameter to limit max connections on WebSocket servers

• new: use new-style classes everywhere

• new: moved package content to repo root

• new: implement router revocation signaling for registrations/subscriptions

• new: a whole bunch of more unit tests / coverage

• new: provide reason/message when transport is lost

• fix: send WAMP errors upon serialization errors

10.62 0.10.1

Published 2015-03-01

• support for pattern-based subscriptions and registrations

• support for shared registrations

• fix: HEARTBEAT removed

10.58. 0.10.5 123

Page 132: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.63 0.10.0

Published 2015-02-19

• Change license from Apache 2.0 to MIT

• fix file line endings

• add setuptools test target

• fix Python 2.6

10.64 0.9.6

Published 2015-02-13

• PEP8 code conformance

• PyFlakes code quality

• fix: warning for xrange on Python 3

• fix: parsing of IPv6 host headers

• add WAMP/Twisted service

• fix: handle connect error in ApplicationRunner (on Twisted)

10.65 0.9.5

Published 2015-01-11

• do not try to fire onClose on a session that never existed in the first place (fixes #316)

• various doc fixes

• fix URI decorator component handling (PR #309)

• fix “standalone” argument to ApplicationRunner

10.66 0.9.4

Published 2014-12-15

• refactor router code to Crossbar.io

• fix: catch error when Nagle cannot be set on stream transport (UDS)

• fix: spelling in doc strings / docs

• fix: WAMP JSON serialization of Unicode for ujson

• fix: Twisted plugins issue

124 Chapter 10. Changelog

Page 133: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.67 0.9.3-2

Published 2014-11-15

• maintenance release with some smaller bug fixes

• use ujson for WAMP when available

• reduce WAMP ID space to [0, 2**31-1]

• deactivate Twisted plugin cache recaching in setup.py

10.68 0.9.3

Published 2014-11-10

• feature: WebSocket origin checking

• feature: allow to disclose caller transport level info

• fix: Python 2.6 compatibility

• fix: handling of WebSocket close frame in a corner-case

10.69 0.9.2

Published 2014-10-17

• fix: permessage-deflate “client_max_window_bits” parameter handling

• fix: cancel opening handshake timeouts also for WebSocket clients

• feature: add more control parameters to Flash policy file factory

• feature: update AutobahnJS in examples

• feature: allow to set WebSocket HTTP headers via dict

• fix: ayncio imports for Python 3.4.2

• feature: added reconnecting WebSocket client example

10.70 0.9.1

Published 2014-09-22

• maintenance release with some smaller bug fixes

10.71 0.9.0

Published 2014-09-02

• all WAMP v1 code removed

• migrated various WAMP examples to WAMP v2

10.67. 0.9.3-2 125

Page 134: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

• improved unicode/bytes handling

• lots of code quality polishment

• more unit test coverage

10.72 0.8.15

Published 2014-08-23

• docs polishing

• small fixes (unicode handling and such)

10.73 0.8.14

Published 2014-08-14

• add automatic WebSocket ping/pong (#24)

• WAMP-CRA client side (beta!)

10.74 0.8.13

Published 2014-08-05

• fix Application class (#240)

• support WSS for Application class

• remove implicit dependency on bzip2 (#244)

10.75 0.8.12

Published 2014-07-23

• WAMP application payload validation hooks

• added Tox based testing for multiple platforms

• code quality fixes

10.76 0.8.11

Published

• hooks and infrastructure for WAMP2 authorization

• new examples: Twisted Klein, Crochet, wxPython

• improved WAMP long-poll transport

• improved stats tracker

126 Chapter 10. Changelog

Page 135: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.77 0.8.10

Published

• WAMP-over-Long-poll (preliminary)

• WAMP Authentication methods CR, Ticket, TOTP (preliminary)

• WAMP App object (preliminary)

• various fixes

10.78 0.8.9

Published

• maintenance release

10.79 0.8.8

Published

• initial support for WAMP on asyncio

• new WAMP examples

• WAMP ApplicationRunner

10.80 0.8.7

Published

• maintenance release

10.81 0.8.6

Published

• started reworking docs

• allow factories to operate without WS URL

• fix behavior on second protocol violation

10.82 0.8.5

Published

• support WAMP endpoint/handler decorators

• new examples for endpoint/handler decorators

• fix excludeMe pubsub option

10.77. 0.8.10 127

Page 136: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.83 0.8.4

Published

• initial support for WAMP v2 authentication

• various fixes/improvements to WAMP v2 implementation

• new example: WebSocket authentication with Mozilla Persona

• polish up documentation

10.84 0.8.3

Published

• fix bug with closing router app sessions

10.85 0.8.2

Published

• compatibility with latest WAMP v2 spec (“RC-2, 2014/02/22”)

• various smaller fixes

10.86 0.8.1

Published

• WAMP v2 basic router (broker + dealer) implementation

• WAMP v2 example set

• WAMP v2: decouple transports, sessions and routers

• support explicit (binary) subprotocol name for wrapping WebSocket factory

• fix dependency on MsgPack

10.87 0.8.0

Published

• new: complete WAMP v2 protocol implementation and API layer

• new: basic WAMP v2 router implementation

• existing WAMP v1 implementation renamed

128 Chapter 10. Changelog

Page 137: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.88 0.7.4

Published

• fix WebSocket server HTML status page

• fix close reason string handling

• new “slowsquare” example

• Python 2.6 fixes

10.89 0.7.3

Published

• support asyncio on Python 2 (via “Trollius” backport)

10.90 0.7.2

Published

• really fix setup/packaging

10.91 0.7.1

Published

• setup fixes

• fixes for Python2.6

10.92 0.7.0

Published

• asyncio support

• Python 3 support

• support WebSocket (and WAMP) over Twisted stream endpoints

• support Twisted stream endpoints over WebSocket

• twistd stream endpoint forwarding plugin

• various new examples

• fix Flash policy factory

10.88. 0.7.4 129

Page 138: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.93 0.6.5

Published

• Twisted reactor is no longer imported on module level (but lazy)

• optimize pure Python UTF8 validator (10-20% speedup on PyPy)

• opening handshake traffic stats (per-open stats)

• add multi-core echo example

• fixes with examples of streaming mode

• fix zero payload in streaming mode

10.94 0.6.4

Published

• support latest permessage-deflate draft

• allow controlling memory level for zlib / permessage-deflate

• updated reference, moved docs to “Read the Docs”

• fixes #157 (a WAMP-CRA timing attack very, very unlikely to be exploitable, but anyway)

10.95 0.6.3

Published

• symmetric RPCs

• WebSocket compression: client and server, permessage-deflate, permessage-bzip2 and permessage-snappy

• onConnect is allowed to return Deferreds now

• custom publication and subscription handler are allowed to return Deferreds now

• support for explicit proxies

• default protocol version now is RFC6455

• option to use salted passwords for authentication with WAMP-CRA

• automatically use ultrajson acceleration package for JSON processing when available

• automatically use wsaccel acceleration package for WebSocket masking and UTF8 validation when available

• allow setting and getting of custom HTTP headers in WebSocket opening handshake

• various new code examples

• various documentation fixes and improvements

130 Chapter 10. Changelog

Page 139: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

10.96 0.5.14

Published

• base version when we started to maintain a changelog

10.96. 0.5.14 131

Page 140: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

132 Chapter 10. Changelog

Page 141: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

Python Module Index

aautobahn.rawsocket.util, 79autobahn.util, 61autobahn.wamp.auth, 96autobahn.wamp.cryptobox, 97autobahn.wamp.cryptosign, 97autobahn.wamp.exception, 94autobahn.wamp.interfaces, 80autobahn.wamp.types, 87autobahn.websocket.compress, 75autobahn.websocket.types, 72autobahn.websocket.util, 78

133

Page 142: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

134 Python Module Index

Page 143: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

Index

Aabort() (autobahn.wamp.interfaces.ITransport

method), 82absolute() (autobahn.util.Tracker method), 63Accept (class in autobahn.wamp.types), 88ApplicationError, 94ApplicationRunner (class in auto-

bahn.asyncio.wamp), 109ApplicationRunner (class in auto-

bahn.twisted.wamp), 104ApplicationSession (class in auto-

bahn.asyncio.wamp), 109ApplicationSession (class in auto-

bahn.twisted.wamp), 103AUTHENTICATION_FAILED (auto-

bahn.wamp.exception.ApplicationError at-tribute), 94

AUTHORIZATION_FAILED (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

AuthScram (class in autobahn.wamp.auth), 96autobahn.rawsocket.util (module), 79autobahn.util (module), 61autobahn.wamp.auth (module), 96autobahn.wamp.cryptobox (module), 97autobahn.wamp.cryptosign (module), 97autobahn.wamp.exception (module), 94autobahn.wamp.interfaces (module), 80autobahn.wamp.types (module), 87autobahn.websocket.compress (module), 75autobahn.websocket.types (module), 72autobahn.websocket.util (module), 78

BBAD_REQUEST (autobahn.websocket.types.ConnectionDeny

attribute), 73BINARY (autobahn.wamp.interfaces.IObjectSerializer

attribute), 80

Ccall() (autobahn.wamp.interfaces.ISession method),

83CallDetails (class in autobahn.wamp.types), 92CallOptions (class in autobahn.wamp.types), 93CallResult (class in autobahn.wamp.types), 93CANCELED (autobahn.wamp.exception.ApplicationError

attribute), 94Challenge (class in autobahn.wamp.types), 88close() (autobahn.wamp.interfaces.ITransport

method), 82CLOSE_REALM (autobahn.wamp.exception.ApplicationError

attribute), 94CloseDetails (class in autobahn.wamp.types), 90Component (class in autobahn.asyncio.component),

105Component (class in autobahn.twisted.component), 100Component (class in autobahn.wamp.component), 98ComponentConfig (class in autobahn.wamp.types),

87compute_totp() (in module autobahn.wamp.auth),

96compute_wcs() (in module autobahn.wamp.auth), 97ConnectionAccept (class in auto-

bahn.websocket.types), 73ConnectionDeny, 73ConnectionRequest (class in auto-

bahn.websocket.types), 72ConnectionResponse (class in auto-

bahn.websocket.types), 73create_url() (in module autobahn.rawsocket.util),

79create_url() (in module autobahn.websocket.util),

78

Ddecode() (autobahn.wamp.interfaces.IPayloadCodec

method), 87define() (autobahn.wamp.interfaces.ISession

135

Page 144: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

method), 83Deny (class in autobahn.wamp.types), 88derive_key() (in module autobahn.wamp.auth), 97diff() (autobahn.util.Tracker method), 64disconnect() (autobahn.wamp.interfaces.ISession

method), 83

Eelapsed() (autobahn.util.Stopwatch method), 63ENC_DECRYPT_ERROR (auto-

bahn.wamp.exception.ApplicationError at-tribute), 94

ENC_NO_PAYLOAD_CODEC (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

ENC_TRUSTED_URI_MISMATCH (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

encode() (autobahn.wamp.interfaces.IPayloadCodecmethod), 87

encode_truncate() (in module autobahn.util), 61EncodedPayload (class in auto-

bahn.wamp.cryptobox), 97EncodedPayload (class in autobahn.wamp.types), 93EqualityMixin (class in autobahn.util), 64Error, 94error_message() (auto-

bahn.wamp.exception.ApplicationErrormethod), 95

EventDetails (class in autobahn.wamp.types), 91

Ffire() (autobahn.util.ObservableMixin method), 64FORBIDDEN (autobahn.websocket.types.ConnectionDeny

attribute), 74from_calldetails() (auto-

bahn.wamp.types.SessionIdent static method),90

from_eventdetails() (auto-bahn.wamp.types.SessionIdent static method),90

Ggenerate_activation_code() (in module auto-

bahn.util), 66generate_serial_number() (in module auto-

bahn.util), 66generate_token() (in module autobahn.util), 65generate_totp_secret() (in module auto-

bahn.wamp.auth), 96generate_user_password() (in module auto-

bahn.util), 66generate_wcs() (in module autobahn.wamp.auth),

97

get_channel_id() (auto-bahn.asyncio.rawsocket.WampRawSocketClientProtocolmethod), 108

get_channel_id() (auto-bahn.asyncio.rawsocket.WampRawSocketServerProtocolmethod), 108

get_channel_id() (auto-bahn.asyncio.websocket.WebSocketClientProtocolmethod), 107

get_channel_id() (auto-bahn.asyncio.websocket.WebSocketServerProtocolmethod), 106

get_channel_id() (auto-bahn.twisted.rawsocket.WampRawSocketClientProtocolmethod), 103

get_channel_id() (auto-bahn.twisted.rawsocket.WampRawSocketServerProtocolmethod), 103

get_channel_id() (auto-bahn.twisted.websocket.WebSocketClientProtocolmethod), 101

get_channel_id() (auto-bahn.twisted.websocket.WebSocketServerProtocolmethod), 101

get_channel_id() (auto-bahn.wamp.interfaces.ITransport method),82

get_extension_string() (auto-bahn.websocket.compress.PerMessageBzip2Offermethod), 77

get_extension_string() (auto-bahn.websocket.compress.PerMessageBzip2OfferAcceptmethod), 78

get_extension_string() (auto-bahn.websocket.compress.PerMessageDeflateOffermethod), 75

get_extension_string() (auto-bahn.websocket.compress.PerMessageDeflateOfferAcceptmethod), 76

get_payload_codec() (auto-bahn.wamp.interfaces.ISession method),83

GOODBYE_AND_OUT (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

HHelloDetails (class in autobahn.wamp.types), 89HelloReturn (class in autobahn.wamp.types), 88

Iid() (in module autobahn.util), 62IdGenerator (class in autobahn.util), 64IMessage (class in autobahn.wamp.interfaces), 81

136 Index

Page 145: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

IncomingMessage (class in auto-bahn.websocket.types), 74

INTERNAL_SERVER_ERROR (auto-bahn.websocket.types.ConnectionDeny at-tribute), 74

INVALID_ARGUMENT (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

INVALID_PAYLOAD (auto-bahn.wamp.exception.ApplicationError at-tribute), 94

INVALID_URI (autobahn.wamp.exception.ApplicationErrorattribute), 95

InvalidUri, 96IObjectSerializer (class in auto-

bahn.wamp.interfaces), 80IPayloadCodec (class in autobahn.wamp.interfaces),

86is_attached() (autobahn.wamp.interfaces.ISession

method), 84is_connected() (auto-

bahn.wamp.interfaces.ISession method),84

ISerializer (class in autobahn.wamp.interfaces), 81ISession (class in autobahn.wamp.interfaces), 83isOpen() (autobahn.wamp.interfaces.ITransport

method), 82ITransport (class in autobahn.wamp.interfaces), 81IWebSocketChannel (class in auto-

bahn.websocket.interfaces), 66IWebSocketClientChannelFactory (class in

autobahn.websocket.interfaces), 70IWebSocketServerChannelFactory (class in

autobahn.websocket.interfaces), 68

Jjoin() (autobahn.wamp.interfaces.ISession method),

84

Lleave() (autobahn.wamp.interfaces.ISession method),

84

MMessage (class in autobahn.websocket.types), 74message_attr() (autobahn.wamp.types.CallOptions

method), 93message_attr() (auto-

bahn.wamp.types.PublishOptions method),92

message_attr() (auto-bahn.wamp.types.RegisterOptions method),92

message_attr() (auto-bahn.wamp.types.SubscribeOptions method),91

MESSAGE_TYPE (autobahn.wamp.interfaces.IMessageattribute), 81

MESSAGE_TYPE_MAP (auto-bahn.wamp.interfaces.ISerializer attribute),81

Nnewid() (in module autobahn.util), 62next() (autobahn.util.IdGenerator method), 65NO_AUTH_METHOD (auto-

bahn.wamp.exception.ApplicationError at-tribute), 95

NO_ELIGIBLE_CALLEE (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_PRINCIPAL (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_PROCEDURE (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_REALM (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_REGISTRATION (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_ROLE (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_SESSION (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NO_SUCH_SUBSCRIPTION (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NOT_ACCEPTABLE (auto-bahn.websocket.types.ConnectionDeny at-tribute), 74

NOT_AUTHORIZED (auto-bahn.wamp.exception.ApplicationError at-tribute), 95

NOT_FOUND (autobahn.websocket.types.ConnectionDenyattribute), 74

NOT_IMPLEMENTED (auto-bahn.websocket.types.ConnectionDeny at-tribute), 74

NotAuthorized, 96

OObservableMixin (class in autobahn.util), 64

Index 137

Page 146: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

off() (autobahn.util.ObservableMixin method), 64on() (autobahn.util.ObservableMixin method), 64on_connect() (auto-

bahn.wamp.component.Component method),99

on_connectfailure() (auto-bahn.wamp.component.Component method),99

on_disconnect() (auto-bahn.wamp.component.Component method),99

on_join() (autobahn.wamp.component.Componentmethod), 99

on_leave() (autobahn.wamp.component.Componentmethod), 99

on_ready() (autobahn.wamp.component.Componentmethod), 99

on_welcome() (autobahn.wamp.auth.AuthScrammethod), 96

onChallenge() (autobahn.wamp.interfaces.ISessionmethod), 84

onClose() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 66

onConnect() (autobahn.wamp.interfaces.ISessionmethod), 84

onConnect() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 66

onConnecting() (auto-bahn.websocket.interfaces.IWebSocketChannelmethod), 67

onDisconnect() (auto-bahn.wamp.interfaces.ISession method),84

onJoin() (autobahn.wamp.interfaces.ISessionmethod), 84

onLeave() (autobahn.wamp.interfaces.ISessionmethod), 84

onMessage() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 67

onOpen() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 67

onPing() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 67

onPong() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 67

onUserError() (autobahn.wamp.interfaces.ISessionmethod), 84

onWelcome() (autobahn.wamp.interfaces.ISessionmethod), 85

OutgoingMessage (class in auto-bahn.websocket.types), 74

Pparse() (autobahn.wamp.interfaces.IMessage static

method), 81parse() (autobahn.websocket.compress.PerMessageBzip2Offer

class method), 77parse() (autobahn.websocket.compress.PerMessageBzip2Response

class method), 78parse() (autobahn.websocket.compress.PerMessageDeflateOffer

class method), 75parse() (autobahn.websocket.compress.PerMessageDeflateResponse

class method), 76parse_url() (in module autobahn.rawsocket.util), 80parse_url() (in module autobahn.websocket.util), 79pause() (autobahn.util.Stopwatch method), 63PAYLOAD_SIZE_EXCEEDED (auto-

bahn.wamp.exception.ApplicationError at-tribute), 95

pbkdf2() (in module autobahn.wamp.auth), 96PerMessageBzip2 (class in auto-

bahn.websocket.compress), 78PerMessageBzip2Offer (class in auto-

bahn.websocket.compress), 77PerMessageBzip2OfferAccept (class in auto-

bahn.websocket.compress), 77PerMessageBzip2Response (class in auto-

bahn.websocket.compress), 78PerMessageBzip2ResponseAccept (class in au-

tobahn.websocket.compress), 78PerMessageCompress (class in auto-

bahn.websocket.compress), 75PerMessageCompressOffer (class in auto-

bahn.websocket.compress), 75PerMessageCompressOfferAccept (class in au-

tobahn.websocket.compress), 75PerMessageCompressResponse (class in auto-

bahn.websocket.compress), 75PerMessageCompressResponseAccept (class in

autobahn.websocket.compress), 75PerMessageDeflate (class in auto-

bahn.websocket.compress), 77PerMessageDeflateOffer (class in auto-

bahn.websocket.compress), 75PerMessageDeflateOfferAccept (class in auto-

bahn.websocket.compress), 75PerMessageDeflateResponse (class in auto-

bahn.websocket.compress), 76PerMessageDeflateResponseAccept (class in

autobahn.websocket.compress), 76PROCEDURE_ALREADY_EXISTS (auto-

bahn.wamp.exception.ApplicationError at-tribute), 95

PROCEDURE_EXISTS_INVOCATION_POLICY_CONFLICT(autobahn.wamp.exception.ApplicationErrorattribute), 95

protocol (autobahn.asyncio.rawsocket.WampRawSocketClientFactoryattribute), 109

138 Index

Page 147: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

protocol (autobahn.asyncio.rawsocket.WampRawSocketServerFactoryattribute), 108

protocol (autobahn.asyncio.websocket.WampWebSocketClientFactoryattribute), 108

protocol (autobahn.asyncio.websocket.WampWebSocketServerFactoryattribute), 108

protocol (autobahn.asyncio.websocket.WebSocketServerFactoryattribute), 107

protocol (autobahn.twisted.rawsocket.WampRawSocketClientFactoryattribute), 103

protocol (autobahn.twisted.rawsocket.WampRawSocketServerFactoryattribute), 103

protocol (autobahn.twisted.websocket.WampWebSocketClientFactoryattribute), 102

protocol (autobahn.twisted.websocket.WampWebSocketServerFactoryattribute), 102

ProtocolError, 94public() (in module autobahn.util), 61publish() (autobahn.wamp.interfaces.ISession

method), 85PublishOptions (class in autobahn.wamp.types), 91

Rregister() (autobahn.wamp.component.Component

method), 99register() (autobahn.wamp.interfaces.ISession

method), 85RegisterOptions (class in autobahn.wamp.types),

92REQUEST_TIMEOUT (auto-

bahn.websocket.types.ConnectionDeny at-tribute), 74

resetProtocolOptions() (auto-bahn.websocket.interfaces.IWebSocketClientChannelFactorymethod), 71

resetProtocolOptions() (auto-bahn.websocket.interfaces.IWebSocketServerChannelFactorymethod), 68

resume() (autobahn.util.Stopwatch method), 63rid() (in module autobahn.util), 62rtime() (in module autobahn.util), 63run() (autobahn.asyncio.wamp.ApplicationRunner

method), 109run() (autobahn.twisted.wamp.ApplicationRunner

method), 104run() (in module autobahn.asyncio.component), 106run() (in module autobahn.twisted.component), 101

Ssend() (autobahn.wamp.interfaces.ITransport

method), 82sendClose() (autobahn.websocket.interfaces.IWebSocketChannel

method), 67

sendMessage() (auto-bahn.websocket.interfaces.IWebSocketChannelmethod), 67

sendPing() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 67

sendPong() (autobahn.websocket.interfaces.IWebSocketChannelmethod), 68

SerializationError, 94serialize() (autobahn.wamp.interfaces.IMessage

method), 81serialize() (autobahn.wamp.interfaces.IObjectSerializer

method), 80serialize() (autobahn.wamp.interfaces.ISerializer

method), 81SERIALIZER_ID (auto-

bahn.wamp.interfaces.ISerializer attribute),81

SERVICE_UNAVAILABLE (auto-bahn.websocket.types.ConnectionDeny at-tribute), 74

session_factory (auto-bahn.asyncio.component.Component at-tribute), 106

session_factory (auto-bahn.twisted.component.Component attribute),100

session_factory (auto-bahn.wamp.component.Component attribute),99

SessionDetails (class in autobahn.wamp.types), 89SessionIdent (class in autobahn.wamp.types), 89SessionNotReady, 94set_payload_codec() (auto-

bahn.wamp.interfaces.ISession method),86

set_valid_events() (auto-bahn.util.ObservableMixin method), 64

setProtocolOptions() (auto-bahn.websocket.interfaces.IWebSocketClientChannelFactorymethod), 71

setProtocolOptions() (auto-bahn.websocket.interfaces.IWebSocketServerChannelFactorymethod), 68

setSessionParameters() (auto-bahn.websocket.interfaces.IWebSocketClientChannelFactorymethod), 72

setSessionParameters() (auto-bahn.websocket.interfaces.IWebSocketServerChannelFactorymethod), 70

start() (autobahn.asyncio.component.Componentmethod), 106

start() (autobahn.twisted.component.Componentmethod), 100

stop() (autobahn.asyncio.wamp.ApplicationRunner

Index 139

Page 148: autobahn - Read the Docs · WAMP is a routed protocol, so you need a WAMP router. We suggest usingCrossbar.io, but there are alsoother We suggest usingCrossbar.io, but there are alsoother

autobahn, Release 19.10.1

method), 110stop() (autobahn.twisted.wamp.ApplicationRunner

method), 105stop() (autobahn.util.Stopwatch method), 63Stopwatch (class in autobahn.util), 63subscribe() (autobahn.wamp.component.Component

method), 99subscribe() (autobahn.wamp.interfaces.ISession

method), 86SubscribeOptions (class in autobahn.wamp.types),

90SYSTEM_SHUTDOWN (auto-

bahn.wamp.exception.ApplicationError at-tribute), 95

TTIMEOUT (autobahn.wamp.exception.ApplicationError

attribute), 95track() (autobahn.util.Tracker method), 64Tracker (class in autobahn.util), 63TransportLost, 94

Uuncache() (autobahn.wamp.interfaces.IMessage

method), 81unserialize() (auto-

bahn.wamp.interfaces.IObjectSerializermethod), 80

unserialize() (auto-bahn.wamp.interfaces.ISerializer method),81

utcnow() (in module autobahn.util), 62utcstr() (in module autobahn.util), 62

WWampRawSocketClientFactory (class in auto-

bahn.asyncio.rawsocket), 108WampRawSocketClientFactory (class in auto-

bahn.twisted.rawsocket), 103WampRawSocketClientProtocol (class in auto-

bahn.asyncio.rawsocket), 108WampRawSocketClientProtocol (class in auto-

bahn.twisted.rawsocket), 103WampRawSocketServerFactory (class in auto-

bahn.asyncio.rawsocket), 108WampRawSocketServerFactory (class in auto-

bahn.twisted.rawsocket), 103WampRawSocketServerProtocol (class in auto-

bahn.asyncio.rawsocket), 108WampRawSocketServerProtocol (class in auto-

bahn.twisted.rawsocket), 102WampWebSocketClientFactory (class in auto-

bahn.asyncio.websocket), 108

WampWebSocketClientFactory (class in auto-bahn.twisted.websocket), 102

WampWebSocketClientProtocol (class in auto-bahn.asyncio.websocket), 107

WampWebSocketClientProtocol (class in auto-bahn.twisted.websocket), 102

WampWebSocketServerFactory (class in auto-bahn.asyncio.websocket), 107

WampWebSocketServerFactory (class in auto-bahn.twisted.websocket), 102

WampWebSocketServerProtocol (class in auto-bahn.asyncio.websocket), 107

WampWebSocketServerProtocol (class in auto-bahn.twisted.websocket), 102

WebSocketClientFactory (class in auto-bahn.asyncio.websocket), 107

WebSocketClientFactory (class in auto-bahn.twisted.websocket), 101

WebSocketClientProtocol (class in auto-bahn.asyncio.websocket), 106

WebSocketClientProtocol (class in auto-bahn.twisted.websocket), 101

WebSocketServerFactory (class in auto-bahn.asyncio.websocket), 107

WebSocketServerFactory (class in auto-bahn.twisted.websocket), 101

WebSocketServerProtocol (class in auto-bahn.asyncio.websocket), 106

WebSocketServerProtocol (class in auto-bahn.twisted.websocket), 101

Xxor() (in module autobahn.util), 61

140 Index